java - Spring Security 和 Oauth2 的误区
问题描述
我目前正在开发一个 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)
内容类型:应用程序/x-www-form-urlencoded
正文:form-data -> 用户名并传递应该是来自数据库的有效用户凭据。如果凭据正确,用户将做出响应
“access_token”:“f0dd6eee-7a64-4079-bb1e-e2cbcca6d7bf”,
"token_type": "承载者",
“expires_in”:86399,
“范围”:“读写信任”
现在我必须将此令牌用于所有其他请求,否则我无权使用该应用程序。
我的问题:这是其他版本的 Spring Security 还是什么?我读到了 OAuth2 身份验证,但我读到一个应用程序可以同时具有 Spring Security 和 OAuth2。如果我们决定实施应用程序安全的方式有问题,有人可以解释一下吗?
非常感谢!
解决方案
是的,你可以认为它是 Spring Security 的不同版本,它取代了标准 Spring Security 的一些策略,例如请求的授权检查。
推荐阅读
- python - Django:如何根据 order_id 获取 order_detail_data
- perl - Perl 证书认证
- c# - 如何减少大量 combobox.selecteditem 属性的样板代码
- c# - C# 仅从 localhost 访问自托管 WCF 登录页面
- ruby - 使用 IRB.conf 设置自定义 .irbrc 的路径
- swift - AVAudioPCMBuffer 只能获取带有静态/白噪声的音频
- excel - 如何在 Excel 中生成具有偏态正态分布的随机数?
- gitlab - gitlab-ci 每分钟安排一次作业
- ios - 添加视图会导致 Storyboard 中的约束更新
- android - 具有动态行数和列数的 Android Horizontal RecyclerView