<error>unauthorized</error>
来源:4-6 搭建OAuth2资源服务器
他门说这就是人生
2019-09-24
我配置了ResourceServerConfigurerAdapter和WebSecurityConfigurerAdapter,但是它不给我跳转到认证服务器的登录页面去,而是报错(如果我直接去登录页面,登陆后跳转到资源服务器的页面还是401):
Full authentication is required to access this resourceunauthorized
以下是我的资源服务器上的配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${auth-server.address}")
private String authServerAddr;
@Value("${client-id}")
private String clientId;
@Value("${client-secret}")
private String clientSecret;
@Bean
public RemoteTokenServices remoteTokenServices() {
RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setClientId(clientId);
remoteTokenServices.setClientSecret(clientSecret);
remoteTokenServices.setCheckTokenEndpointUrl(authServerAddr + "/oauth/token");
return remoteTokenServices;
}
@Bean
public AuthenticationManager authenticationManager() {
OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager();
oAuth2AuthenticationManager.setTokenServices(remoteTokenServices());
return oAuth2AuthenticationManager;
}
}@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private RestTemplate restTemplate=new RestTemplate();
@Autowired
private ObjectMapper objectMapper;
@Value("${auth-server.address}")
private String serverAddr;
@Value("${client-id}")
private String clientId;
@Value("${client-secret}")
private String clientSecret;
@Override
public void configure(HttpSecurity http) throws Exception {
String allMenusStr = ApiRequestUtils.getBodyByBasicAuth(restTemplate, clientId, clientSecret, serverAddr + UrlConsts.MENU_URL, HttpMethod.GET, null,null);
List allMenus = objectMapper.readValue(allMenusStr, new TypeReference() {
});
ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http
.authorizeRequests()
.antMatchers("/**/*.js", "/**/*.css", "/**/*.png", "/**/*.jpg", "/**/*.gif", "/**/*.ico").permitAll()
.antMatchers(HttpMethod.POST, "/logout").permitAll();
allMenus.forEach(sysMenu -> {
expressionInterceptUrlRegistry.antMatchers(sysMenu.getUrl()).access("hasAuthority('" + sysMenu.getPerms() + "')");
});
expressionInterceptUrlRegistry.anyRequest().authenticated()
.and()
.logout().deleteCookies("AUTHSERVERJSESSIONID").deleteCookies("JSESSIONID").logoutSuccessUrl(serverAddr + UrlConsts.LOGOUT_PROCESSOR_URL)
.and()
.csrf().disable();
}
}请问这是什么原因?怎么解决呢?
ps: 贴出授权服务器配置:
@Configuration
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Qualifier("authServerUserDetailsServiceImpl")
@Autowired
private UserDetailsService userDetailsService;
@Value("${default-jump-url}")
private String defaultJumpUrl;
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private LoginSuccessfulHandler loginSuccessfulHandler;
@Autowired
private LoginFailureHandler loginFailureHandler;
@Bean("passwordEncoder")
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().loginPage(UrlConsts.LOGIN_PAGE_URL).loginProcessingUrl(UrlConsts.LOGIN_PROCESSOR_URL)
.successHandler(loginSuccessfulHandler).failureHandler(loginFailureHandler)
.and()
.logout().deleteCookies("AUTHSERVERJSESSIONID").deleteCookies("JSESSIONID")
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, UrlConsts.LOGIN_PAGE_URL, UrlConsts.MENU_URL).permitAll()
.antMatchers(HttpMethod.POST, UrlConsts.LOGIN_PROCESSOR_URL).permitAll()
.antMatchers(UrlConsts.LOGOUT_PROCESSOR_URL,
"/**/*.js", "/**/*.css", "/**/*.png", "/**/*.jpg", "/**/*.gif", "/**/*.ico",
UrlConsts.SWAGGER_UI_URL, UrlConsts.SWAGGER_API_URL, UrlConsts.SWAGGER_RESOURCE_URL, UrlConsts.SWAGGER_WEBJARS_URL).permitAll()
.antMatchers(UrlConsts.MENU_URL + "/**", UrlConsts.USER_URL + "/**", UrlConsts.ROLE_URL + "/**").authenticated();
http.authorizeRequests().anyRequest().authenticated()
.and()
// 记住一小时,一小时内不用重复登录
.rememberMe().userDetailsService(userDetailsService).tokenValiditySeconds(60 * 60)
.and()
.csrf().disable()
.headers().frameOptions().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(jwtTokenStore()).accessTokenConverter(jwtAccessTokenConverter());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("isAuthenticated()");
}
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("xxx");
return converter;
}
}写回答
1回答
-
这里你的理解可能有点问题,资源服务器是处理服务请求的,登录跳转不应该发生在资源服务器,而应该发生在客户端应用。你的配置里也没有跳转的配置。如果你想让资源服务器跳转登录页,应该在资源服务器配置@EnableOAuth2SSO,但是这么配是不对的,因为角色错位了。
00
相似问题