JWT
基础
实践
# 生成公私钥keytool -genkeypair -alias demo -keyalg RSA -keypass demopass -keystore demo.jks -storepass demopass# 查询证书信息keytool -list -keystore demo.jks# 删除别名keytool -delete -alias demo -keystore demo.jks# 导出公钥keytool -list -rfc -keystore demo.jks | openssl x509 -inform pem -pubkey
AuthorizationServer
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>t31-parent</artifactId> <groupId>com.demo</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>t31-auth-center</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!--SpringCloud ailibaba nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!--nacos-config--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <!--SpringCloud ailibaba sentinel --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <!--oauth2--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.kaikeba</groupId> <artifactId>t31-admin-instance</artifactId> <version>${project.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <nonFilteredFileExtensions> <nonFilteredFileExtension>jks</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin> </plugins> </build></project>
bootstrap.yaml
# bootstrap.yamlspring: application: name: auth-center profiles: active: dev cloud: nacos: config: server-addr: localhost:8848 file-extension: yaml extension-configs[0]: data-id: common.yaml refresh: true extension-configs[1]: data-id: db.yaml refresh: true # 多个接口上的@FeignClient(“相同服务名”)会报错,overriding is disabled。 # 设置 为true ,即 允许 同名 main: allow-bean-definition-overriding: true
启动类
package com.demo.t31.auth;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.openfeign.EnableFeignClients;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;@SpringBootApplication@EnableDiscoveryClient@EnableFeignClients@EnableCircuitBreakerpublic class AuthApplication { public static void main(String[] args) { SpringApplication.run(AuthApplication.class, args); }}
配置类
@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfiguration.class); @Autowired @Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager; @Autowired private DataSource dataSource; @Bean public TokenStore tokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); } @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("kaikeba.jks"), "kaikeba".toCharArray());//证书路径和密钥库密码 JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setKeyPair(keyStoreKeyFactory.getKeyPair("kaikeba"));//密钥别名 return converter; } @Bean public ClientDetailsService clientDetailsService() { return new JdbcClientDetailsService(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { //配置通过表oauth_client_details,读取客户端数据 clients.withClientDetails(clientDetailsService()); } /** * 配置token service和令牌存储方式(tokenStore * @param endpoints * @throws Exception */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { //tokenStore endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtAccessTokenConverter()).authenticationManager(authenticationManager); //tokenService DefaultTokenServices tokenServices = new DefaultTokenServices(); tokenServices.setTokenStore(endpoints.getTokenStore()); tokenServices.setSupportRefreshToken(false); tokenServices.setClientDetailsService(endpoints.getClientDetailsService()); tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer()); tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30)); // 30天 endpoints.tokenServices(tokenServices); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { // 允许表单认证 security.allowFormAuthenticationForClients() //放行oauth/token_key(获得公钥) .tokenKeyAccess("permitAll()") //放行 oauth/check_token(验证令牌)// .checkTokenAccess("isAuthenticated()"); .checkTokenAccess("permitAll()"); }}
@Configuration@EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter { /** * 注入自定义UserDetailService,读取rbac数据 */ @Autowired private UserDetailsService userDetailsService; @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatchers().anyRequest() .and().authorizeRequests().antMatchers("/oauth/**").permitAll();//开放/oauth/开头的所有请求 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //注入自定义的UserDetailsService,采用BCrypt加密 auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); }}
service
@Servicepublic class UserDetailServiceImpl implements UserDetailsService { private static final Logger logger = LoggerFactory.getLogger(UserDetailServiceImpl.class); @Autowired UserClient userClient; @Autowired PasswordEncoder passwordEncoder;//BCryptPasswordEncoder @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { com.kaikeba.t31.admin.po.User user = userClient.getByUserName(username); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); if (user != null) { logger.debug("current user = " + user); //获取用户的授权 List<Role> roles = userClient.selectRolesByUserId(user.getId()); //声明授权文件 for (Role role : roles) { if (role != null && role.getName() != null) { GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + role.getName());//spring Security中权限名称必须满足ROLE_XXX grantedAuthorities.add(grantedAuthority); } } } logger.debug("granted authorities = " + grantedAuthorities); return new User(user.getUserName(), user.getPassword(), grantedAuthorities); }}
@FeignClient(name = "admin-service", fallback = UserClient.UserClientFallback.class)public interface UserClient extends UserApi { @Component @RequestMapping("/fallback") //这个可以避免容器中requestMapping重复 class UserClientFallback implements UserClient { private static final Logger LOGGER = LoggerFactory.getLogger(UserClientFallback.class); @Override public User getByUserName(String userName) { LOGGER.info("异常发生,进入fallback方法"); return null; } @Override public List<Role> selectRolesByUserId(Long id) { LOGGER.info("异常发生,进入fallback方法"); return null; } }}
ResourceServer
配置类
@Configurationpublic class JwtConfig { public static final String public_cert = "public.key"; @Autowired private JwtAccessTokenConverter jwtAccessTokenConverter; @Bean @Qualifier("tokenStore") public TokenStore tokenStore() { return new JwtTokenStore(jwtAccessTokenConverter); } @Bean protected JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); Resource resource = new ClassPathResource(public_cert); String publicKey; try { publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); }catch (IOException e) { throw new RuntimeException(e); } // 设置校验公钥 converter.setVerifierKey(publicKey); // 设置证书签名密码,否则报错 converter.setSigningKey("demopass"); return converter; }}
@Configuration@EnableResourceServer@EnableGlobalMethodSecurity(prePostEnabled = true)# Spring Security中定义了四个支持权限控制的表达式注解,分别是# @PreAuthorize# @PostAuthorize# @PreFilter# @PostFilter# 其中前两者可以用来在方法调用前或者调用后进行权限检查# 后两者可以用来对集合类型的参数或者返回值进行过滤。# 要使用需要先配置@EnableGlobalMethodSecurity(prePostEnabled = true)public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired private TokenStore tokenStore; @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() // .antMatchers("/**").permitAll(); .antMatchers("/user/**").permitAll() .antMatchers("/book/**").hasRole("ADMIN") //用于测试 ,全局控制,可以使用@PreAuthorize方法级别控制 .antMatchers("/**").authenticated(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.tokenStore(tokenStore); }}
security.yaml
security: oauth2: resource: jwt: key-uri: http://localhost:9098/oauth/token_key #如果使用JWT,可以获取公钥用于 token 的验签
用户登录
配置
security: oauth2: client: access-token-uri: http://localhost:9098/oauth/token #令牌端点 user-authorization-uri: http://localhost:9098/oauth/authorize #授权端点 client-id: client client-secret: 123456 grant-type: password scope: read,write
登录方法
@RestController@RequestMapping("/user")public class UserController extends BaseController<IUserService, User> { @Autowired private OAuth2ClientProperties oAuth2ClientProperties; @Autowired private OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails; @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Autowired private RestTemplate restTemplate; @Autowired private IMenuService menuService; @RequestMapping("/login") public ResponseEntity<OAuth2AccessToken> login(String username, String password) { // 1:验证用户 User user = service.getUserByUserName(username); if (null == user) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } if (!BPwdEncoderUtil.matches(password, user.getPassword())) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } // 2:使用restTemplate发送请求到授权服务器,申请令牌 // 请求头 "basic auth" String client_secret = oAuth2ClientProperties.getClientId() + ":" + oAuth2ClientProperties.getClientSecret(); client_secret = "Basic " + Base64.getEncoder().encodeToString(client_secret.getBytes()); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", client_secret); //请求参数 MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.put("username", Collections.singletonList(username)); map.put("password", Collections.singletonList(password)); map.put("grant_type", Collections.singletonList(oAuth2ProtectedResourceDetails.getGrantType())); map.put("scope",oAuth2ProtectedResourceDetails.getScope()); // HttpEntity(请求参数,头。。。) HttpEntity httpEntity = new HttpEntity(map, headers); return restTemplate.exchange(oAuth2ProtectedResourceDetails.getAccessTokenUri(), HttpMethod.POST, httpEntity, OAuth2AccessToken.class); }}
前端实现
