gpt4 book ai didi

java - Spring Boot端点未经过身份验证

转载 作者:行者123 更新时间:2023-12-02 10:51:06 25 4
gpt4 key购买 nike

我正在尝试学习oauth2以及jwt,所以我的引用链接是

https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example

我正在使用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());
}
}

ResourceServerConfig

@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;
}
}

现在当我调用时使用这些配置

http://localhost:8080/oauth/token

这使我能够访问和刷新,这正是我想要的。但现在

我有一个看起来像的 Controller

 @GetMapping("/users")
public Map<String,String> getUsers(){
Map<String,String> map = new HashMap<>();
map.put("name","sagar");
map.put("job","developers");
return map;
}

所以我像这样调用这个端点

http://localhost:8080/users

现在我期望的是,每当我调用此端点时,该调用都应该经过身份验证。但它只是返回我

{
"name": "sagar",
"job": "developers"
}

即使我不发送任何 token 。我希望允许具有角色 SCT_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)

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api- docs/**").permitAll().anyRequest().authenticated();
}

并且不要忘记修复您拥有 access("hasRole('SCT_USER')") 的 ResourceServerConfig 中的拼写错误

而不是

access("hasRole('USER')")

我已经为您的代码创建了测试示例。 https://github.com/alex-petrov81/stackoverflow-answers/tree/master/spring-boot-endpoint-not-auth

关于java - Spring Boot端点未经过身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52178049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com