赞
踩
项目整体文件结构:
config:配置文件包
entity:实体模型
mapper:数据处理层
service impl:接口实现层
创建认证服务器类:AuthorizationServerConfiguration
package com.lichi.auth.config; import com.lichi.auth.entity.CustomTokenEnhancer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import javax.annotation.Resource; import javax.sql.DataSource; import java.util.Arrays; /** * 认证服务器 * @author lichi * @create 2021-07-06 15:37 */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Resource private DataSource dataSource; @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenStore jwtTokenStore; @Autowired private JwtAccessTokenConverter jwtAccessTokenConverter; public ClientDetailsService clientDetailsService() { return new JdbcClientDetailsService(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.withClientDetails(clientDetailsService()); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { TokenEnhancerChain enhancerChain = new TokenEnhancerChain(); enhancerChain.setTokenEnhancers(Arrays.asList(customTokenEnhancer(), jwtAccessTokenConverter)); endpoints .authenticationManager(authenticationManager) .tokenStore(jwtTokenStore) .tokenEnhancer(enhancerChain); } /** * 配置令牌端点的安全约束 * @param security * @throws Exception */ @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security .tokenKeyAccess("permitAll()")//tokenKey这个endpoint完全公开 .checkTokenAccess("permitAll()")//checkToken这个endpoint完全公开 .allowFormAuthenticationForClients();//允许表单验证 } public TokenEnhancer customTokenEnhancer() { return new CustomTokenEnhancer(); } }
创建配置类:WebSecurityConfiguration
package com.lichi.auth.config; import com.lichi.auth.service.impl.UserDetailsServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; /** * @author lichi * @create 2021-07-06 12:38 */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public UserDetailsService userDetailsService() { return new UserDetailsServiceImpl(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()); } @Bean @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/**").authenticated() .and() .formLogin().permitAll() .and() .csrf().disable(); } }
创建资源服务器类:ResourceServerConfiguration
package com.lichi.auth.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; /** * @author lichi * @create 2021-07-06 15:45 */ @Configuration @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { //资源id,对应的是数据库客户端配置表 public static final String RESOURCE_ID = "res"; @Autowired private TokenStore tokenStore; @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.tokenStore(tokenStore) .resourceId(RESOURCE_ID) .stateless(false); } @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated().and() .requestMatchers().antMatchers("/api/**"); } }
创建Jwt配置类:JwtTokenConfig
package com.lichi.auth.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; /** * @author lichi * @create 2021-07-06 15:40 */ @Configuration public class JwtTokenConfig { private static final String SIGN_KEY = "lichi"; @Bean public JwtTokenStore jwtTokenStore(){ return new JwtTokenStore(jwtAccessTokenConverter()); } @Bean public JwtAccessTokenConverter jwtAccessTokenConverter(){ JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey(SIGN_KEY); return converter; } }
Security校验用户信息过程核心类:UserDetailsServiceImpl
package com.lichi.auth.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.lichi.auth.entity.CustomUserDetails; import com.lichi.auth.entity.Permission; import com.lichi.auth.entity.TbUser; import com.lichi.auth.mapper.UserMapper; import com.lichi.auth.service.PermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import java.util.ArrayList; import java.util.List; /** * @author lichi * @create 2021-07-06 12:39 */ public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserMapper userMapper; @Autowired private PermissionService permissionService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>(); wrapper.eq(TbUser::getUsername,username); TbUser user = userMapper.selectOne(wrapper); if (user == null) return null; List<Permission> permissionList = permissionService.queryByUserId(user.getId()); List<String> permissions = new ArrayList<>(); if (permissionList != null && !permissionList.isEmpty()) permissionList.stream().forEach(permission -> { permissions.add(permission.getEnname()); }); return new CustomUserDetails(user.getId(), username, user.getPassword(), user.getName(), user.getPhone(), permissions); } }
完整代码在我的码云上面:https://gitee.com/lichilichi/cookie
我们跑起来代码之后可以进行postman进行自测:
第一步:获取token
第二步:check_token
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。