Я пытаюсь реализовать OAuth2 в приложении весенней загрузки. Пока я могу получить токен доступа и получить доступ к URL, но я запутался, когда я включаю конфигурацию сервера ресурсов в моем приложении, тогда пользователь с ролью USER может получить доступ к странице ADMIN и наоборот. и Authentication
устанавливается на true
с authentication.getName()
возвращением на username
с oauth2
запросом grant_type=password
Framework:
- весенний ботинок
- Spring Security Web
- Spring Security Config
- Spring Security OAuth2
Мой код указан ниже:
SecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private LoginRepository loginRepository;
@Autowired
private TestLoginService testLoginService;
@Autowired
private DaoAuthenticationProvider daoAuthenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/register").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
protected UserDetailsService userDetailsService() {
loginRepository.init(encoder());
return testLoginService;
}
@Bean
public DaoAuthenticationProvider customAuthenticationProvider() {
final DaoAuthenticationProvider customAuthenticationProvider = new DaoAuthenticationProvider();
customAuthenticationProvider.setUserDetailsService(testLoginService);
customAuthenticationProvider.setPasswordEncoder(encoder());
return customAuthenticationProvider;
}
@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
OAuth2SecurityConfig.java
@Configuration
@EnableAuthorizationServer
public class OAuth2SecurityConfig extends AuthorizationServerConfigurerAdapter {
private static Logger logger = LoggerFactory.getLogger(OAuth2SecurityConfig.class);
@Autowired
private TokenStore tokenStore;
@Autowired
private AuthenticationManager AuthenticationManager;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.authenticationManager(AuthenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String secret = passwordEncoder.encode("secret");
logger.info("Secret : " + secret);
clients
.inMemory()
.withClient("client")
.secret("$2a$10$8ip4rySjPLcCedGRVgvT8OriH7dB2VoWDQfk7V3mvPx/BBV8Yglry")
.autoApprove(false)
.authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
.scopes(Role.ROLE_USER.name(), Role.ROLE_ADMIN.name())
.redirectUris("http://localhost:8080/code")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(4800);
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
}
OAuth2ResourceSecurityConfig.java
@Configuration
@EnableResourceServer
public class OAuth2ResourceSecurityConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated();
}
}
Если я не настрою метод OAuth2ResourceSecurityConfig # configure, тогда пользователи ролей пользователя или администратора могут получить доступ к любому из URL. Может кто-нибудь объяснить, пожалуйста, актуальность метода настройки в OAuth2ResourceSecurityConfig
и SecurityConfig
и какой из них следует использовать для большей ясности.
SecurityController.java
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminAccess(Authentication authentication) {
logger.info("Admin access /admin link: " + authentication.getName() + " role: " + authentication.getAuthorities().toString());
logger.info("Admin User authenticated: " + authentication.isAuthenticated());
return authentication.getName();
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String userAccess(Authentication authentication) {
logger.info("User access / : " + authentication.getName() + " role: " + authentication.getAuthorities().toString());
logger.info("User authenticated: " + authentication.isAuthenticated());
return authentication.getName();
}
Спасибо.