【发布时间】:2018-11-02 01:16:39
【问题描述】:
我想使用 OAth2 实现 spring rest api 的安全性,我对这些概念非常陌生。我已经使用 InMemoryAuthentication 实现了这个概念,它工作正常,但我正在尝试使用 jdbc 身份验证。在google上搜索了这么多教程后,我实现了jdbc身份验证,但它给出了错误,我不知道该怎么做,我的代码如下所示。我不确定我的流程是否正确,请纠正我.
AuthorizationServerConfig 类
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws
Exception {
clients.inMemory()
.withClient("crmClient1")
.secret("crmSuperSecret")
.authorizedGrantTypes("password", "refresh_token")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
//.accessTokenValiditySeconds(ONE_DAY)
.accessTokenValiditySeconds(300)
.refreshTokenValiditySeconds(THIRTY_DAYS);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.realm(REALM);
}
}
ResourceServerConfig 类
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
//-- define URL patterns to enable OAuth2 security
http.
anonymous().disable()
.requestMatchers().antMatchers("/api/**")
.and().authorizeRequests()
.antMatchers("/api/**").access("hasRole('ADMIN') or hasRole('USER')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
SecurityConfig 类
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private DataSource dataSource;
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("data source : " + dataSource.getConnection().isClosed());
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password from users where username=?");
/*auth.jdbcAuthentication().dataSource(dataSource)
.authoritiesByUsernameQuery("select username, role from user_roles where username =?");*/
}
/* @Autowired
public void globalUserDetails(AuthenticationManagerBuilder
auth) throws Exception {
//System.out.println("Auth : "+auth.inMemoryAuthentication().toString());
auth.inMemoryAuthentication()
.withUser("crmadmin").password("crmpass").roles("ADMIN","USER").and()
.withUser("crmuser").password("pass123").roles("USER");
}*/
@Override
@Order(Ordered.HIGHEST_PRECEDENCE)
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable()
.authorizeRequests().antMatchers("/about").permitAll().antMatchers("/signup").permitAll()
.antMatchers("/oauth/token").permitAll()
// .antMatchers("/api/**").authenticated()
// .antMatchers("/api/**").hasRole("USER")
.anyRequest().authenticated().and().httpBasic().realmName("CRM_REALM");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@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;
}
}
邮递员结果
【问题讨论】:
标签: spring-security oauth-2.0 spring-jdbc spring-restcontroller