引入maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR12</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
新增 spring security配置类 SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/doLogin")
.successHandler(new MyAuthenticationSuccessHandler())
.defaultSuccessUrl("/index")
.failureUrl("/login.html")
.failureHandler(new MyAuthenticationFailureHandler())
.usernameParameter("uname")
.passwordParameter("passwd")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessUrl("/mylogin.html")
.logoutSuccessHandler(((httpServletRequest, httpServletResponse, authentication) -> {
httpServletResponse.setContentType("application/json;charset=utf-8");
Map<String, Object> resp = new HashMap<>();
resp.put("status", 500);
resp.put("msg", "注销成功");
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(resp);
httpServletResponse.getWriter().write(s);
}))
.permitAll()
.and()
.csrf().disable();
http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
设置数据库用户认证
新增 MyUserDetailsService,验证用户信息
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String orgCode)
throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(orgCode);
if (user == null) {
throw new UsernameNotFoundException("柜员不存在");
}
user.setRoles(userMapper.getRolesByUid(user.getId()));
OauthAspect.setUserDetails(user);
return user;
}
}
在SecurityConfig配置类中,加入以下配置
@Autowired
MyUserDetailsService myUserDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService);
}
忽略文件 在SecurityConfig配置类中,加入以下配置
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/login.html", "/css/**", "/js/**","/images/**");
}
设置加密在SecurityConfig配置类中,加入以下配置
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
配置spring security oauht2认证服务器
新增 AuthorizationServerConfig
客户端基于内存配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("admin")
.secret(passwordEncoder.encode("112233"))
.redirectUris("http://www.baidu.com")
.scopes("all")
.authorizedGrantTypes("authorization_code","password", "refresh_token");
}
}
客户端基于数据库配置,AuthorizationServerConfig添加以下配置
@Bean
ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
将token信息存redis
新增 RedisTokenStoreConfig
@Configuration
public class RedisTokenStoreConfig {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public TokenStore redisTokenStore(){
return new RedisTokenStore(redisConnectionFactory);
}
}
AuthorizationServerConfig添加以下配置
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.userDetailsService(myUserDetailsService)
.tokenStore(tokenStore);
}
设置check_token端点
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()");
security.checkTokenAccess("isAuthenticated()");
}
配置spring security oauth2 资源服务器
新增OAuth2ResourceServer
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.requestMatchers()
.antMatchers("/order/**");
}
}
在配置文件加入配置
security:
oauth2:
client:
client-id: admin
client-secret: 112233
access-token-uri: http://localhost:7775/oauth/token
grant-type: password
scope: all
resource:
token-info-uri: http://localhost:7775/oauth/check_token