Spring-boot身份验证

时间:2018-01-25 13:42:26

标签: spring spring-mvc spring-boot spring-security spring-web

我有很少的Spring-boot控制器类来公开很少的休息网络服务。每当某个用户尝试访问任何这些服务时,我都需要调用Web服务来检查用户(用户ID是否将作为RequestHeader传递)是否被授权。如果未获得授权,则需要向用户显示错误页面(freemarker模板)。

我不想编写一个方法,该方法将调用身份验证Web服务并从每个控制器方法调用该方法并抛出异常并使用@ControllerAdvice将用户重定向到访问被拒绝错误页面,因为我必须调用所有控制器方法的方法。

我不确定是否可以使用WebSecurityConfigurerAdapter / AuthenticationManagerBuilder来调用Web服务并进行验证。

我正在寻找一些解决方案,我会编写一个拦截器,spring-boot将在调用控制器类之前调用​​webservice,并且如果验证失败,将能够重定向到错误页面。

1 个答案:

答案 0 :(得分:-1)

作为一个建议,花几分钟阅读有关Spring Security(https://projects.spring.io/spring-security/)的内容,你必须配置它,可能你会花费比预期更多的时间,无论如何你拥有的利润远远超过我们自己的安全性。

好处是:

@PreAuthorize("hasRole('ROLE_USER')")

在每个地方,您都可以通过SecurityContext登录用户:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();

SpringSecurity对用户进行身份验证的方式是使用JWT(JsonWebToken),这是一种非常好的方式,因为您可以传递和检索所需的所有信息:

public class CustomTokenEnhancer implements TokenEnhancer {

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    User user = (User) authentication.getPrincipal();
    final Map<String, Object> additionalInfo = new HashMap<>();

    additionalInfo.put("customInfo", "some_stuff_here");
    additionalInfo.put("authorities", user.getAuthorities());

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

    return accessToken;
}

}

你可以忘记每一个可能的问题(错误的身份验证,网络钓鱼,xss或csrf ..)因为它可以使用公钥/私钥和秘密,所以任何人都可以创建一个令牌。