</parent>

2.2公共工程創建

然后創建一個common工程,其他工程依賴此系統

SpringSecurity + JWT 實現單點登錄

導入JWT相關的依賴

<dependencies><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-api</artifactId><version>0.10.7</version></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-impl</artifactId><version>0.10.7</version><scope>runtime</scope></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId><version>0.10.7</version><scope>runtime</scope></dependency><!--jackson包--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.9</version></dependency><!--日志包--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></dependency><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency></dependencies>

創建相關的工具類

SpringSecurity + JWT 實現單點登錄

Payload

@Datapublic class Payload <T>{private String id;private T userInfo;private Date expiration;}

JsonUtils

public classJsonUtils{public static final ObjectMapper mapper = new ObjectMapper;private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);public static String toString(Object obj) {if (obj == ) {return ;}if (obj.getClass == String.class) {return (String) obj;}try {return mapper.writeValueAsString(obj);} catch (JsonProcessingException e) {logger.error("json序列化出錯:" + obj, e);return ;}}public static <T> T toBean(String json, Class<T> tClass) {try {return mapper.readValue(json, tClass);} catch (IOException e) {logger.error("json解析出錯:" + json, e);return ;}}public static <E> List<E> toList(String json, Class<E> eClass) {try {return mapper.readValue(json, mapper.getTypeFactory.constructCollectionType(List.class, eClass));} catch (IOException e) {logger.error("json解析出錯:" + json, e);return ;}}public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {try {return mapper.readValue(json, mapper.getTypeFactory.constructMapType(Map.class, kClass, vClass));} catch (IOException e) {logger.error("json解析出錯:" + json, e);return ;}}public static <T> T nativeRead(String json, TypeReference<T> type) {try {return mapper.readValue(json, type);} catch (IOException e) {logger.error("json解析出錯:" + json, e);return ;}}}

JwtUtils

public classJwtUtils{private static final String JWT_PAYLOAD_USER_KEY = "user";/*** 私鑰加密token** @param userInfo 載荷中的數據* @param privateKey 私鑰* @param expire 過期時間,單位分鐘* @return JWT*/public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {return Jwts.builder.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo)).setId(createJTI).setExpiration(DateTime.now.plusMinutes(expire).toDate).signWith(privateKey, SignatureAlgorithm.RS256).compact;}/*** 私鑰加密token** @param userInfo 載荷中的數據* @param privateKey 私鑰* @param expire 過期時間,單位秒* @return JWT*/public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {return Jwts.builder.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo)).setId(createJTI).setExpiration(DateTime.now.plusSeconds(expire).toDate).signWith(privateKey, SignatureAlgorithm.RS256).compact;}/*** 公鑰解析token** @param token 用戶請求中的token* @param publicKey 公鑰* @return Jws<Claims>*/private static Jws<Claims> parserToken(String token, PublicKey publicKey) {return Jwts.parser.setSigningKey(publicKey).parseClaimsJws(token);}private static String createJTI {return new String(Base64.getEncoder.encode(UUID.randomUUID.toString.getBytes));}/*** 獲取token中的用戶信息** @param token 用戶請求中的令牌* @param publicKey 公鑰* @return 用戶信息*/public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {Jws<Claims> claimsJws = parserToken(token, publicKey);Claims body = claimsJws.getBody;Payload<T> claims = new Payload<>;claims.setId(body.getId);claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString, userType));claims.setExpiration(body.getExpiration);return claims;}/*** 獲取token中的載荷信息** @param token 用戶請求中的令牌* @param publicKey 公鑰* @return 用戶信息*/public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {Jws<Claims> claimsJws = parserToken(token, publicKey);Claims body = claimsJws.getBody;Payload<T> claims = new Payload<>;claims.setId(body.getId);claims.setExpiration(body.getExpiration);return claims;}}

RsaUtils

public classRsaUtils{private static final int DEFAULT_KEY_SIZE = 2048;/*** 從文件中讀取公鑰** @param filename 公鑰保存路徑,相對于classpath* @return 公鑰對象* @throws Exception*/public static PublicKey getPublicKey(String filename) throws Exception {byte bytes = readFile(filename);return getPublicKey(bytes);}/*** 從文件中讀取密鑰** @param filename 私鑰保存路徑,相對于classpath* @return 私鑰對象* @throws Exception*/public static PrivateKey getPrivateKey(String filename) throws Exception {byte bytes = readFile(filename);return getPrivateKey(bytes);}/*** 獲取公鑰** @param bytes 公鑰的字節形式* @return* @throws Exception*/private static PublicKey getPublicKey(byte[] bytes) throws Exception {bytes = Base64.getDecoder.decode(bytes);X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);KeyFactory factory = KeyFactory.getInstance("RSA");return factory.generatePublic(spec);}/*** 獲取密鑰** @param bytes 私鑰的字節形式* @return* @throws Exception*/private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {bytes = Base64.getDecoder.decode(bytes);PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);KeyFactory factory = KeyFactory.getInstance("RSA");return factory.generatePrivate(spec);}/*** 根據密文,生存rsa公鑰和私鑰,并寫入指定文件** @param publicKeyFilename 公鑰文件路徑* @param privateKeyFilename 私鑰文件路徑* @param secret 生成密鑰的密文*/public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize) throws Exception {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");SecureRandom secureRandom = new SecureRandom(secret.getBytes);keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);KeyPair keyPair = keyPairGenerator.genKeyPair;// 獲取公鑰并寫出byte publicKeyBytes = keyPair.getPublic.getEncoded;publicKeyBytes = Base64.getEncoder.encode(publicKeyBytes);writeFile(publicKeyFilename, publicKeyBytes);// 獲取私鑰并寫出byte privateKeyBytes = keyPair.getPrivate.getEncoded;privateKeyBytes = Base64.getEncoder.encode(privateKeyBytes);writeFile(privateKeyFilename, privateKeyBytes);}private static byte readFile(String fileName) throws Exception {return Files.readAllBytes(new File(fileName).toPath);}private static void writeFile(String destPath, byte[] bytes) throws IOException {File dest = new File(destPath);if (!dest.exists) {dest.createNewFile;}Files.write(dest.toPath, bytes);}}

在通用子模塊中編寫測試類生成rsa公鑰和私鑰

public classJwtTest{private String privateKey = "c:/tools/auth_key/id_key_rsa";private String publicKey = "c:/tools/auth_key/id_key_rsa.pub";@Testpublic void test1 throws Exception{RsaUtils.generateKey(publicKey,privateKey,"dpb",1024);}}
SpringSecurity + JWT 實現單點登錄

2.3認證系統創建

接下來我們創建我們的認證服務。

SpringSecurity + JWT 實現單點登錄

導入相關的依賴

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><artifactId>security-jwt-common</artifactId><groupId>com.dpb</groupId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency></dependencies>

創建配置文件

spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/srmusername: rootpassword: 123456type: com.alibaba.druid.pool.DruidDataSourcemybatis:type-aliases-package: com.dpb.domainmapper-locations: classpath:mapper/*.xmllogging:level:com.dpb: debugrsa:key:pubKeyFile: c:toolsauth_keyid_key_rsa.pubpriKeyFile: c:toolsauth_keyid_key_rsa
SpringSecurity + JWT 實現單點登錄

提供公鑰私鑰的配置類

@Data@ConfigurationProperties(prefix = "rsa.key")publicclassRsaKeyProperties{private String pubKeyFile;private String priKeyFile;private PublicKey publicKey;private PrivateKey privateKey;/*** 系統啟動的時候觸發* @throws Exception*/@PostConstructpublic void createRsaKey throws Exception {publicKey = RsaUtils.getPublicKey(pubKeyFile);privateKey = RsaUtils.getPrivateKey(priKeyFile);}}

創建啟動類

@SpringBootApplication@MapperScan("com.dpb.mapper")@EnableConfigurationProperties(RsaKeyProperties.class)public class App {public static void main(String[] args) {SpringApplication.run(App.class,args);}}

完成數據認證的邏輯

pojo

@Datapublic class RolePojo implements GrantedAuthority {private Integer id;private String roleName;private String roleDesc;@JsonIgnore@Overridepublic String getAuthority {return roleName;}}
@DatapublicclassUserPojoimplementsUserDetails{private Integer id;private String username;private String password;private Integer status;private List<RolePojo> roles;@JsonIgnore@Overridepublic Collection<? extends GrantedAuthority> getAuthorities {List<SimpleGrantedAuthority> auth = new ArrayList<>;auth.add(new SimpleGrantedAuthority("ADMIN"));return auth;}@Overridepublic String getPassword {return this.password;}@Overridepublic String getUsername {return this.username;}@JsonIgnore@OverridepublicbooleanisAccountNonExpired {return true;}@JsonIgnore@OverridepublicbooleanisAccountNonLocked {return true;}@JsonIgnore@OverridepublicbooleanisCredentialsNonExpired {return true;}@JsonIgnore@OverridepublicbooleanisEnabled {return true;}}

Mapper接口

public interface UserMapper {public UserPojo queryByUserName(@Param("userName") String userName);}

Mapper映射文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.dpb.mapper.UserMapper"><select id="queryByUserName" resultType="UserPojo">select * from t_user where username = #{userName}</select></mapper>

Service

public interfaceUserServiceextendsUserDetailsService{}
@Service@TransactionalpublicclassUserServiceImplimplementsUserService{@Autowiredprivate UserMapper mapper;@Overridepublic UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {UserPojo user = mapper.queryByUserName(s);return user;}}

自定義認證過濾器

public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {private AuthenticationManager authenticationManager;private RsaKeyProperties prop;public TokenLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {this.authenticationManager = authenticationManager;this.prop = prop;}public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {try {UserPojo sysUser = new ObjectMapper.readValue(request.getInputStream, UserPojo.class);UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername, sysUser.getPassword);return authenticationManager.authenticate(authRequest);}catch (Exception e){try {response.setContentType("application/json;charset=utf-8");response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);PrintWriter out = response.getWriter;Map resultMap = new HashMap;resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);resultMap.put("msg", "用戶名或密碼錯誤!");out.write(new ObjectMapper.writeValueAsString(resultMap));out.flush;out.close;}catch (Exception outEx){outEx.printStackTrace;}throw new RuntimeException(e);}}public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {UserPojo user = new UserPojo;user.setUsername(authResult.getName);user.setRoles((List<RolePojo>)authResult.getAuthorities);String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey, 24 * 60);response.addHeader("Authorization", "Bearer "+token);try {response.setContentType("application/json;charset=utf-8");response.setStatus(HttpServletResponse.SC_OK);PrintWriter out = response.getWriter;Map resultMap = new HashMap;resultMap.put("code", HttpServletResponse.SC_OK);resultMap.put("msg", "認證通過!");out.write(new ObjectMapper.writeValueAsString(resultMap));out.flush;out.close;}catch (Exception outEx){outEx.printStackTrace;}}}

自定義校驗token的過濾器

public class TokenVerifyFilter extends BasicAuthenticationFilter {private RsaKeyProperties prop;public TokenVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {super(authenticationManager);this.prop = prop;}public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {String header = request.getHeader("Authorization");if (header == || !header.startsWith("Bearer ")) {//如果攜帶錯誤的token,則給用戶提示請登錄!chain.doFilter(request, response);response.setContentType("application/json;charset=utf-8");response.setStatus(HttpServletResponse.SC_FORBIDDEN);PrintWriter out = response.getWriter;Map resultMap = new HashMap;resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);resultMap.put("msg", "請登錄!");out.write(new ObjectMapper.writeValueAsString(resultMap));out.flush;out.close;} else {//如果攜帶了正確格式的token要先得到tokenString token = header.replace("Bearer ", "");//驗證tken是否正確Payload<UserPojo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey, UserPojo.class);UserPojo user = payload.getUserInfo;if(user!=){UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(user.getUsername, , user.getAuthorities);SecurityContextHolder.getContext.setAuthentication(authResult);chain.doFilter(request, response);}}}}

編寫SpringSecurity的配置類

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(securedEnabled=true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserService userService;@Autowiredprivate RsaKeyProperties prop;@Beanpublic BCryptPasswordEncoder passwordEncoder{return new BCryptPasswordEncoder;}//指定認證對象的來源public void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService).passwordEncoder(passwordEncoder);}//SpringSecurity配置信息public void configure(HttpSecurity http) throws Exception {http.csrf.disable.authorizeRequests.antMatchers("/user/query").hasAnyRole("ADMIN").anyRequest.authenticated.and.addFilter(new TokenLoginFilter(super.authenticationManager, prop)).addFilter(new TokenVerifyFilter(super.authenticationManager, prop)).sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS);}}

啟動服務測試

啟動服務

SpringSecurity + JWT 實現單點登錄

通過Postman來訪問測試

SpringSecurity + JWT 實現單點登錄
SpringSecurity + JWT 實現單點登錄

根據token信息我們訪問其他資源

SpringSecurity + JWT 實現單點登錄

2.4資源系統創建

說明

資源服務可以有很多個,這里只拿產品服務為例,記住,資源服務中只能通過公鑰驗證認證。不能簽發token!創建產品服務并導入jar包根據實際業務導包即可,咱們就暫時和認證服務一樣了。

接下來我們再創建一個資源服務

SpringSecurity + JWT 實現單點登錄

導入相關的依賴

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><artifactId>security-jwt-common</artifactId><groupId>com.dpb</groupId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency></dependencies>

編寫產品服務配置文件

切記這里只能有公鑰地址!

server:port: 9002spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/srmusername: rootpassword: 123456type: com.alibaba.druid.pool.DruidDataSourcemybatis:type-aliases-package: com.dpb.domainmapper-locations: classpath:mapper/*.xmllogging:level:com.dpb: debugrsa:key:pubKeyFile: c:toolsauth_keyid_key_rsa.pub

編寫讀取公鑰的配置類

@Data@ConfigurationProperties(prefix = "rsa.key")publicclassRsaKeyProperties{private String pubKeyFile;private PublicKey publicKey;/*** 系統啟動的時候觸發* @throws Exception*/@PostConstructpublic void createRsaKey throws Exception {publicKey = RsaUtils.getPublicKey(pubKeyFile);}}

編寫啟動類

@SpringBootApplication@MapperScan("com.dpb.mapper")@EnableConfigurationProperties(RsaKeyProperties.class)public class App {public static void main(String[] args) {SpringApplication.run(App.class,args);}}

復制認證服務中,用戶對象,角色對象和校驗認證的接口

復制認證服務中的相關內容即可

復制認證服務中SpringSecurity配置類做修改

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(securedEnabled=true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserService userService;@Autowiredprivate RsaKeyProperties prop;@Beanpublic BCryptPasswordEncoder passwordEncoder{return new BCryptPasswordEncoder;}//指定認證對象的來源public void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService).passwordEncoder(passwordEncoder);}//SpringSecurity配置信息public void configure(HttpSecurity http) throws Exception {http.csrf.disable.authorizeRequests//.antMatchers("/user/query").hasAnyRole("USER").anyRequest.authenticated.and.addFilter(new TokenVerifyFilter(super.authenticationManager, prop))// 禁用掉session.sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS);}}

去掉“增加自定義認證過濾器”即可!

編寫產品處理器

@RestController@RequestMapping("/user")publicclassUserController{@RequestMapping("/query")public String query{return "success";}@RequestMapping("/update")public String update{return "update";}}

測試

SpringSecurity + JWT 實現單點登錄
(0)

相關推薦

版權聲明:本文內容由互聯網用戶自發貢獻,該文觀點僅代表作者本人。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如發現本站有涉嫌抄襲侵權/違法違規的內容, 請發送郵件至 舉報,一經查實,本站將立刻刪除。

發表評論

登錄后才能評論
国产精品区一区二区免费