我目前正在开发一个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
Headers:基本btoa(pfjA@Dmin,4gM~$laY{gnfShpa%8Pcjwcz-J.NVS)
Content-Type : application/x-www-form-urlencoded
正文:表单-数据->用户名,传递的应该是来自数据库的有效用户凭据。如果凭证是正确的,则用户将作出响应
"access_token":"f0dd6eee-7a64-4079-bb1e-e2cbcca6d7bf",
"token_type":“持有者”,
"expires_in":86399,
"scope":“读写信任”
现在,我必须对所有其他请求使用这个令牌,否则我没有任何权限使用该应用程序。
我的问题是:这是Spring Security的另一个版本吗?我读到过关于OAuth2身份验证的文章,但是我读到一个应用程序可以同时拥有Spring Security和OAuth2。有没有人能给我解释一下,我们决定实现应用安全的方式是否有问题?
非常感谢!
发布于 2019-02-17 01:12:19
是的,你可以认为它是spring安全的不同版本,它取代了标准spring安全的一些策略,比如请求的授权检查。
https://stackoverflow.com/questions/54711388
复制相似问题