Spring 安全仅用于授权。外部认证

Tos*_*tis 6 security authentication spring authorization external

正如标题所说,我正在开发一个从外部应用程序接收用户身份验证信息的 Web 应用程序。我的应用程序的弹簧控制器获取用户信息并将其存储在会话中。我想在 Spring Security 中对这个用户进行身份验证,然后使用他的角色来授予/拒绝对 url 的访问,例如

<intercept-url pattern="/myprotectedpage*" access="hasRole('rightrole')" />
Run Code Online (Sandbox Code Playgroud)

我阅读了一些关于 PRE_AUTH_FILTER 和 UserDetailsS​​ervice 的教程,但我不明白这一点。Spring Security 的应用生命周期是怎样的?涉及哪些课程?我需要一些完整的工作样本。

mar*_*eig 0

实现保存用户信息的服务。

@Service
public class UserAuthenticationInfoService {

    private final Map<String, UserInfo> infos = new HashMap<String, UserInfo>();

    public void addUserInfo(UserInfo userInfo){
        infos.put(userInfo.getUsername(), userInfo);   
    }

    public UserInfo getUserInfo(String username) {
        return infos.get(username);
    }

}
Run Code Online (Sandbox Code Playgroud)

您的控制器使用您从外部应用程序收到的用户信息填充 UserAuthenticationInfoService 服务。

然后实现自定义 UserDetailsS​​ervice 来访问这些信息。

public class CustomerUserDetailsService implements UserDetailsService {
    @Autowired
    private UserAuthenticationInfoService service;

     public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        UserInfo info = service.getUserInfo(userName);
        return new User(info.getUsername(), info.getPassword(), info.getAuthorities());
    }
}
Run Code Online (Sandbox Code Playgroud)

并设置 spring security 上下文以使用此 UserDetailsS​​ervice (您可以在 spring security 文档中找到它)