Java Spring引导终结点未经过身份验证
我正在尝试学习Java Spring引导终结点未经过身份验证,java,spring-boot,oauth-2.0,jwt,Java,Spring Boot,Oauth 2.0,Jwt,我正在尝试学习oauth2以及jwt,因此我的参考链接是 我使用的是spring boot 1.5.15 授权服务器配置 @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { static final String CLIEN_ID = "devglan-client"; st
oauth2
以及jwt
,因此我的参考链接是
我使用的是spring boot 1.5.15
授权服务器配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIEN_ID = "devglan-client";
static final String CLIENT_SECRET = "devglan-secret";
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("as466gf");
return converter;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.inMemory()
.withClient(CLIEN_ID)
.secret(CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).
refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
}
@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("/users").access("hasRole('SCT_USER')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityHandler securityHandler;
@Autowired
private UserSecurityService userSecurityService;
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/images/**",
"/",
"**/",
"/newUser",
"/forgetPassword",
"/login",
"**/uploads/**",
"/assets/**",
"/api/updateCardStatus",
"/fonts/**",
"/users"
};
/* @Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
*//* antMatchers("/**").*//*
.antMatchers(PUBLIC_MATCHERS).
permitAll().anyRequest().authenticated();
http
.authorizeRequests()
.antMatchers("/admin").hasAnyRole("ROLE_ADMIN").and()
.formLogin().loginPage("/login").permitAll().failureUrl("/login?error")
.successHandler(securityHandler)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api-docs/**").permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception{
web.ignoring()
.antMatchers("/api/updateCardStatus","*/uploads/***","/api/getUsersDetail","/api/getStudentDetails","/api/getAccountLoad","/api/issueDirectives","/api/changePassword","/api/cardActivation","/api/CustomerAccountCardDetails","/api/accountLoad","/api/updateConsumersProfile","/api/verifyCvv"
,"/api/updatePrepaidCardStatus","/api/getStatementData");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(SecurityUtils.passwordEncoder());
}
@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;
}
}
ResourceServerConfig
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIEN_ID = "devglan-client";
static final String CLIENT_SECRET = "devglan-secret";
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("as466gf");
return converter;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.inMemory()
.withClient(CLIEN_ID)
.secret(CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).
refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
}
@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("/users").access("hasRole('SCT_USER')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityHandler securityHandler;
@Autowired
private UserSecurityService userSecurityService;
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/images/**",
"/",
"**/",
"/newUser",
"/forgetPassword",
"/login",
"**/uploads/**",
"/assets/**",
"/api/updateCardStatus",
"/fonts/**",
"/users"
};
/* @Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
*//* antMatchers("/**").*//*
.antMatchers(PUBLIC_MATCHERS).
permitAll().anyRequest().authenticated();
http
.authorizeRequests()
.antMatchers("/admin").hasAnyRole("ROLE_ADMIN").and()
.formLogin().loginPage("/login").permitAll().failureUrl("/login?error")
.successHandler(securityHandler)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api-docs/**").permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception{
web.ignoring()
.antMatchers("/api/updateCardStatus","*/uploads/***","/api/getUsersDetail","/api/getStudentDetails","/api/getAccountLoad","/api/issueDirectives","/api/changePassword","/api/cardActivation","/api/CustomerAccountCardDetails","/api/accountLoad","/api/updateConsumersProfile","/api/verifyCvv"
,"/api/updatePrepaidCardStatus","/api/getStatementData");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(SecurityUtils.passwordEncoder());
}
@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;
}
}
现在,当我调用
这给了我访问和刷新,这是我想要的。但是现在
我有一个控制器,看起来像
@GetMapping("/users")
public Map<String,String> getUsers(){
Map<String,String> map = new HashMap<>();
map.put("name","sagar");
map.put("job","developers");
return map;
}
即使我没有寄任何代币。我希望允许该端点使用角色SCT\u USER
为什么不发生这种情况?请仔细查看我的SecurityConfig版本
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientDetailsService clientDetailsService;
/*@Autowired
private SecurityHandler securityHandler;
@Autowired
private UserSecurityService userSecurityService;
*/
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/images/**",
"/",
"**/",
"/newUser",
"/forgetPassword",
"/login",
"**/uploads/**",
"/assets/**",
"/api/updateCardStatus",
"/fonts/**",
"/users"
};
/* @Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
*//* antMatchers("/**").*//*
.antMatchers(PUBLIC_MATCHERS).
permitAll().anyRequest().authenticated();
http
.authorizeRequests()
.antMatchers("/admin").hasAnyRole("ROLE_ADMIN").and()
.formLogin().loginPage("/login").permitAll().failureUrl("/login?error")
.successHandler(securityHandler)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api-docs/**").permitAll().anyRequest().authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception{
web.ignoring()
.antMatchers("/api/updateCardStatus","*/uploads/***","/api/getUsersDetail","/api/getStudentDetails","/api/getAccountLoad","/api/issueDirectives","/api/changePassword","/api/cardActivation","/api/CustomerAccountCardDetails","/api/accountLoad","/api/updateConsumersProfile","/api/verifyCvv"
,"/api/updatePrepaidCardStatus","/api/getStatementData");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password("pass")
.roles("ADMIN", "USER").and()
.withUser("appuser")
.password("pass123").roles("USER");
}
/*@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(SecurityUtils.passwordEncoder());
}*/
@Bean
public PasswordEncoder encoder(){
return NoOpPasswordEncoder.getInstance();
}
@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;
}
@Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
}
这里有两点很重要
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
及
不要忘了在ResourceServerConfig中修复您的输入错误,您可以在那里访问(“hasRole('SCT_USER')”)
而不是
access("hasRole('USER')")
我已经为您的代码创建了测试示例。
我并没有提供Securityconfig类的代码。仔细检查您的代码后,我发现了一个错误:hasRole(“SCT_用户”),但在您的凭据中,您使用的是用户角色。我会很快地改变我的答案,这就解决了它。非常感谢。花了我几个小时,我仍然无法发现它们。这个@Order注释做什么?在1.5.x版之后,OAuth2资源服务器Order被设置为SecurityProperties.ACCESS\u OVERRIDE\u Order-1,它现在的优先级肯定低于基本WebSecurity配置适配器顺序。因此,需要指定@Order注释来恢复WebSecurity配置适配器顺序。它在Spring过滤器链中启用了OAuth过滤器。看来,这个顺序的东西弄乱了我的其他URL。就像我调用localhost:8080/admin一样,它之前打开了admin.html页面。但在保留order注释之后,它现在返回一些xml错误。我怎么说例如**(将其视为api)和其他url是正常的重定向url