我是Spring Boot的新手,我正在尝试配置OAuth 2.0。我可以使用访问令牌访问API,但是在尝试访问JSP页面时却收到403。
AuthorizationServerConfig.java
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("QWERTY");
return converter;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer.inMemory().withClient(Utils.CLIEN_ID).secret(Utils.CLIENT_SECRET).authorities("ADMIN", "AGENT")
.authorizedGrantTypes(Utils.GRANT_TYPE_PASSWORD, Utils.AUTHORIZATION_CODE, Utils.REFRESH_TOKEN,
Utils.IMPLICIT)
.scopes(Utils.SCOPE_READ, Utils.SCOPE_WRITE, Utils.TRUST)
.accessTokenValiditySeconds(Utils.ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(Utils.FREFRESH_TOKEN_VALIDITY_SECONDS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
}
WebSecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "userService")
private UserDetailsService userDetailsService;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().anonymous().disable().authorizeRequests()
.antMatchers("/auth/**").hasRole("ADMIN");
}
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
UserDetailServiceImplementation.java
@Service(value = "userService")
public class UserDetailServiceImplementation implements UserDetailsService {
@Autowired
private UserRepository userRepository;
public UserDetailServiceImplementation() {
super();
}
@Override
public UserDetails loadUserByUsername(String sLoginID) throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user = userRepository.findByLoginID(sLoginID);
if (user == null) {
throw new UsernameNotFoundException(sLoginID);
}
return new org.springframework.security.core.userdetails.User(sLoginID, user.getsPassword(),
getAuthorities(user.getiUserTypeID()));
}
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 1) {
roles.add("ROLE_AGENT");
roles.add("ROLE_ADMIN");
} else if (role.intValue() == 2) {
roles.add("ROLE_MANAGER");
}
return roles;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
ResourceServerConfig.java
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "resource_id";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.anonymous().disable().authorizeRequests()
.antMatchers("/auth/admin/**").access("hasRole('ROLE_ADMIN')").and().exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
当我尝试在Postman和RestTemplate中访问oauth / token时,我能够检索到access_token和其他参数。我的应用程序的控制器部分有RestTemplate,当我们重定向到任何页面时,它会基于API从API检索数据,由于hasRole函数,它被禁止。是否需要为JSP页面实现单独的安全配置?