Spring Security和Oauth2的误解

时间:2019-02-15 14:27:05

标签: java spring-boot spring-security-oauth2 spring-security-rest

我目前正在处理Spring Boot应用程序,并且我要负责执行应用程序的安全性。他们建议使用OAuth2令牌身份验证,即使在我设法通过其他spring安全教程创建安全性的其他应用程序中也是如此。 这是根据我在不同来源找到的教程创建的:

public class OAuthPermissionConfig extends ResourceServerConfigurerAdapter 

@Override
public void configure(HttpSecurity http) throws Exception {
    http.anonymous().disable()
            .authorizeRequests()
            .antMatchers("/pim/oauth/token").permitAll().and().formLogin()
            .and().authorizeRequests().antMatchers("/actuator/**", "/v2/api-docs", "/webjars/**",
            "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-ui.html",
            "/swagger-resources/configuration/security").hasAnyAuthority("ADMIN")
            .anyRequest().authenticated();
}





 public class CustomAuthenticationProvider implements AuthenticationProvider 

@Autowired
private ADService adService;

@Autowired
private UserService userService;

@Override
@Transactional
public Authentication authenticate(Authentication authentication) {
    try {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        User user = userService.getUserByUsername(username);
        userService.isUserAllowedToUseTheApplication(user);
        if (adService.isUserNearlyBlockedInAD(user)) {
            throw new BadCredentialsException(CustomMessages.TOO_MANY_LOGIN_FAILED);
        } else {
            adService.login(username, password);
        }
        List<GrantedAuthority> userAuthority = user.getRoles().stream()
                .map(p -> new SimpleGrantedAuthority(p.getId())).collect(Collectors.toList());
        return new LoginToken(user, password, userAuthority);
    } catch (NoSuchDatabaseEntryException | NullArgumentException | NamingException | EmptyUserRolesException e) {
        throw new BadCredentialsException(CustomMessages.INVALID_CREDENTIALS + " or " + CustomMessages.UNAUTHORIZED);
    }
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(
            UsernamePasswordAuthenticationToken.class);
}





@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}




public class OAuthServerConfig extends AuthorizationServerConfigurerAdapter 

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private UserService userService;

@Autowired
private PasswordEncoder passwordEncoder;

@Bean
public TokenEnhancer tokenEnhancer() {
    return new CustomTokenEnhancer();
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    endpoints.authenticationManager(authenticationManager).tokenEnhancer(tokenEnhancer());
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

    clients
            .inMemory()
            .withClient("pfjA@Dmin")
            .secret(passwordEncoder.encode("4gM~$laY{gnfShpa%8Pcjwcz-J.NVS"))
            .authorizedGrantTypes("password")
            .accessTokenValiditySeconds(UTILS.convertMinutesToSeconds(1440))
            .scopes("read", "write", "trust")
            .resourceIds("oauth2-resource");
}

@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
    security.checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();
}

在测试登录时,我使用具有以下参数的邮递员:

http://localhost:8080/oauth/token?grant_type=password

标题:基本btoa(pfjA @ Dmin,4gM〜$ laY {gnfShpa%8Pcjwcz-J.NVS)

Content-Type:应用程序/ x-www-form-urlencoded

正文:表单数据->用户名并通过 应该是来自数据库的有效用户凭据。 如果凭据正确,用户将做出响应

“ access_token”:“ f0dd6eee-7a64-4079-bb1e-e2cbcca6d7bf”,

“ token_type”:“ bearer”,

“ expires_in”:86399,

“作用域”:“读写信任”

现在我必须对所有其他请求使用此令牌,否则我就没有使用该应用程序的权限。

我的问题:这是Spring Security的另一个版本还是什么?我读到有关OAuth2身份验证的信息,但我看到一个应用程序可以同时具有Spring Security和OAuth2。如果我们决定实现应用安全性的方式有问题,可以请人解释一下吗?

非常感谢您!

1 个答案:

答案 0 :(得分:1)

是的,您可以认为它是Spring Security的不同版本,它替代了标准Spring Security的某些策略,例如对请求的授权检查。