Spring Security和Oauth2的误解

问题描述 投票:0回答:1

我目前正在开发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();
}

在测试登录时,我使用postman这个参数:

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

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

内容类型:application / x-www-form-urlencoded

正文:表单数据 - >用户名和传递,应该是数据库中的有效用户凭据。如果凭据正确,用户将做出响应

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

“token_type”:“bearer”,

“expires_in”:86399,

“范围”:“读写信任”

现在我必须将此令牌用于所有其他请求,否则我没有任何权限来使用该应用程序。

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

非常感谢你!

java spring-boot spring-security-oauth2 spring-security-rest
1个回答
1
投票

是的,您可以认为它是弹簧安全性的不同版本,它取代了标准弹簧安全性的一些策略,例如请求的授权检查。

© www.soinside.com 2019 - 2024. All rights reserved.