简体   繁体   English

Spring Security和Oauth2的误解

[英]Spring Security and Oauth2 misunderstanding

I am currently working on a Spring Boot application and I have the task to do the security of the application. 我目前正在开发Spring Boot应用程序,并且我要负责执行应用程序的安全性。 They suggested to use OAuth2 token authentification even thought in other applications I manage to create the security with other spring security tutorial. 他们建议使用OAuth2令牌身份验证,即使在我设法通过其他spring安全教程创建安全性的其他应用程序中也是如此。 This are created based on tutorials I found on different sources: 这是根据我在不同来源找到的教程创建的:

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();
}

When testing the login, I use postman with this parameters : 在测试登录时,我使用具有以下参数的邮递员:

http://localhost:8080/oauth/token?grant_type=password HTTP://本地主机:8080 /的OAuth /令牌grant_type =密码

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

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

Body: form-data -> username and pass that should be a valid user credentials from the database. 正文:form-data-> username和pass,应该是数据库中的有效用户凭据。 And the user will respond if the credentials are correct 如果凭据正确,用户将做出响应

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

"token_type": "bearer", “ token_type”:“承载者”,

"expires_in": 86399, “ expires_in”:86399,

"scope": "read write trust" “ scope”:“读写信任”

Now I have to use this token for all the other requests otherwise I dont have any permision to use the application. 现在,我必须对所有其他请求使用此令牌,否则我将无法使用该应用程序。

My question: Is this other version of Spring Security or what? 我的问题:这是Spring Security的另一个版本还是什么? I read about OAuth2 authentication but I read that an application can have BOTH Spring Security and OAuth2. 我读到有关OAuth2身份验证的信息,但我看到一个应用程序可以同时具有Spring Security和OAuth2。 Can someone please explain me if there is something wrong with the way we decided to implement the app security? 如果我们决定实现应用安全性的方式有问题,可以请人解释一下吗?

Thank you very much! 非常感谢你!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM