hippo4j-auth CheckStyle (#940)

* style:hippo4j-auth CheckStyle

* style:hippo4j-auth CheckStyle
pull/941/head
WuLang 2 years ago committed by GitHub
parent c559110ba0
commit d9a37dbeba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -35,4 +35,4 @@ public class FilterConfig {
registration.addUrlPatterns("/*"); registration.addUrlPatterns("/*");
return registration; return registration;
} }
} }

@ -27,4 +27,6 @@ public class Constants {
public static final String SPLIT_COMMA = ","; public static final String SPLIT_COMMA = ",";
public static final long TOKEN_VALIDITY_IN_SECONDS = 18000L; public static final long TOKEN_VALIDITY_IN_SECONDS = 18000L;
public static final long STEP = 1000L;
} }

@ -96,7 +96,7 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
String token = JwtTokenUtil.createToken(jwtUser.getId(), jwtUser.getUsername(), role, isRemember); String token = JwtTokenUtil.createToken(jwtUser.getId(), jwtUser.getUsername(), role, isRemember);
response.setHeader("token", JwtTokenUtil.TOKEN_PREFIX + token); response.setHeader("token", JwtTokenUtil.TOKEN_PREFIX + token);
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
Map<String, Object> maps = new HashMap(MAP_INITIAL_CAPACITY); Map<String, Object> maps = new HashMap<>(MAP_INITIAL_CAPACITY);
maps.put("data", JwtTokenUtil.TOKEN_PREFIX + token); maps.put("data", JwtTokenUtil.TOKEN_PREFIX + token);
maps.put("roles", role.split(SPLIT_COMMA)); maps.put("roles", role.split(SPLIT_COMMA));
response.getWriter().write(JSONUtil.toJSONString(Results.success(maps))); response.getWriter().write(JSONUtil.toJSONString(Results.success(maps)));
@ -108,6 +108,6 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
@Override @Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException { protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSONUtil.toJSONString(new ReturnT(-1, "Server Error"))); response.getWriter().write(JSONUtil.toJSONString(new ReturnT(ReturnT.JWT_FAIL_CODE, "Server Error")));
} }
} }

@ -59,22 +59,28 @@ public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
protected void doFilterInternal(HttpServletRequest request, protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, HttpServletResponse response,
FilterChain chain) throws IOException, ServletException { FilterChain chain) throws IOException, ServletException {
boolean checkAccessTokenOrTokenHeader = false;
// Token when verifying client interaction. // Token when verifying client interaction.
String accessToken = request.getParameter(ACCESS_TOKEN); String accessToken = request.getParameter(ACCESS_TOKEN);
String tokenHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
if (StringUtil.isNotBlank(accessToken)) { if (StringUtil.isNotBlank(accessToken)) {
tokenManager.validateToken(accessToken); tokenManager.validateToken(accessToken);
Authentication authentication = this.tokenManager.getAuthentication(accessToken); Authentication authentication = this.tokenManager.getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response); checkAccessTokenOrTokenHeader = true;
return; } else if (checkTokenHeader(tokenHeader)) {
// If there is no Authorization information in the request header, it will be released directly.
checkAccessTokenOrTokenHeader = true;
} }
// If there is no Authorization information in the request header, it will be released directly. if (checkAccessTokenOrTokenHeader) {
String tokenHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
chain.doFilter(request, response); chain.doFilter(request, response);
return; } else {
filterInternal(request, response, chain, tokenHeader);
} }
// If there is a Token in the request header, it is parsed and the authentication information is set. }
private void filterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
String tokenHeader) throws IOException, ServletException {
try { try {
SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader)); SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
} catch (Exception ex) { } catch (Exception ex) {
@ -90,17 +96,21 @@ public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
return; return;
} }
try { try {
super.doFilterInternal(request, response, chain); doFilterInternal(request, response, chain);
} finally { } finally {
UserContext.clear(); UserContext.clear();
} }
} }
private boolean checkTokenHeader(String tokenHeader) {
return tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX);
}
/** /**
* Obtain user information from Token and create a new Token. * Obtain user information from Token and create a new Token.
* *
* @param tokenHeader * @param tokenHeader tokenHeader
* @return * @return UsernamePasswordAuthenticationToken
*/ */
private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) { private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {
String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, ""); String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");

@ -19,14 +19,18 @@ package cn.hippo4j.auth.filter;
import cn.hippo4j.auth.toolkit.AuthUtil; import cn.hippo4j.auth.toolkit.AuthUtil;
import javax.servlet.*; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.IOException; import java.io.IOException;
/** /**
* When anonymous login is enabled, an error will be reported when viewing the current user information. * When anonymous login is enabled, an error will be reported when viewing the current user information.
* Modify the URI to query the default administrator information. * Modify the URI to query the default administrator information.
* * <p>
* before:hippo4j/v1/cs/auth/users/info or hippo4j/v1/cs/auth/users/info/xxx * before:hippo4j/v1/cs/auth/users/info or hippo4j/v1/cs/auth/users/info/xxx
* after:hippo4j/v1/cs/auth/users/info/admin * after:hippo4j/v1/cs/auth/users/info/admin
*/ */
@ -34,7 +38,7 @@ public class RewriteUserInfoApiFilter implements Filter {
@Override @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
boolean enableAuthentication = AuthUtil.ENABLE_AUTHENTICATION; boolean enableAuthentication = AuthUtil.isEnableAuthentication();
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
String path = httpRequest.getRequestURI(); String path = httpRequest.getRequestURI();
if (!enableAuthentication && path.contains("users/info")) { if (!enableAuthentication && path.contains("users/info")) {
@ -43,4 +47,4 @@ public class RewriteUserInfoApiFilter implements Filter {
} }
filterChain.doFilter(servletRequest, servletResponse); filterChain.doFilter(servletRequest, servletResponse);
} }
} }

@ -17,7 +17,12 @@
package cn.hippo4j.auth.model; package cn.hippo4j.auth.model;
import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.util.Date;

@ -17,7 +17,12 @@
package cn.hippo4j.auth.model; package cn.hippo4j.auth.model;
import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.util.Date;

@ -17,7 +17,12 @@
package cn.hippo4j.auth.model; package cn.hippo4j.auth.model;
import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.util.Date;

@ -31,6 +31,7 @@ import org.springframework.stereotype.Component;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import static cn.hippo4j.auth.constant.Constants.STEP;
import static cn.hippo4j.auth.constant.Constants.TOKEN_VALIDITY_IN_SECONDS; import static cn.hippo4j.auth.constant.Constants.TOKEN_VALIDITY_IN_SECONDS;
import static cn.hippo4j.auth.toolkit.JwtTokenUtil.SECRET; import static cn.hippo4j.auth.toolkit.JwtTokenUtil.SECRET;
import static cn.hippo4j.common.constant.Constants.AUTHORITIES_KEY; import static cn.hippo4j.common.constant.Constants.AUTHORITIES_KEY;
@ -50,14 +51,13 @@ public class JwtTokenManager {
public String createToken(String userName) { public String createToken(String userName) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Date validity; Date validity;
validity = new Date(now + TOKEN_VALIDITY_IN_SECONDS * 1000L); validity = new Date(now + TOKEN_VALIDITY_IN_SECONDS * STEP);
Claims claims = Jwts.claims().setSubject(userName); Claims claims = Jwts.claims().setSubject(userName);
String token = Jwts.builder() return Jwts.builder()
.setClaims(claims) .setClaims(claims)
.setExpiration(validity) .setExpiration(validity)
.signWith(SignatureAlgorithm.HS512, SECRET) .signWith(SignatureAlgorithm.HS512, SECRET)
.compact(); .compact();
return token;
} }
/** /**

@ -29,10 +29,14 @@ public class AuthUtil {
/** /**
* Enable authentication * Enable authentication
*/ */
public static boolean ENABLE_AUTHENTICATION; private static boolean enableAuthentication;
@Value("${hippo4j.core.auth.enabled:true}") @Value("${hippo4j.core.auth.enabled:true}")
public void setEnableAuthentication(boolean enabled) { public void setEnableAuthentication(boolean enabled) {
AuthUtil.ENABLE_AUTHENTICATION = enabled; AuthUtil.enableAuthentication = enabled;
} }
}
public static boolean isEnableAuthentication() {
return enableAuthentication;
}
}

@ -77,7 +77,7 @@ public class JwtTokenUtil {
.setIssuer(ISS) .setIssuer(ISS)
.setSubject(id + Constants.SPLIT_COMMA + username) .setSubject(id + Constants.SPLIT_COMMA + username)
.setIssuedAt(new Date()) .setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) .setExpiration(new Date(System.currentTimeMillis() + expiration * Constants.STEP))
.compact(); .compact();
} }

@ -35,6 +35,8 @@ public class ReturnT<T> implements Serializable {
public static final int FAIL_CODE = 500; public static final int FAIL_CODE = 500;
public static final int JWT_FAIL_CODE = -1;
public static final ReturnT<String> SUCCESS = new ReturnT<>(null); public static final ReturnT<String> SUCCESS = new ReturnT<>(null);
public static final ReturnT<String> FAIL = new ReturnT<>(FAIL_CODE, null); public static final ReturnT<String> FAIL = new ReturnT<>(FAIL_CODE, null);

@ -33,6 +33,6 @@ public final class AuthUtilTest {
@Test @Test
public void assertGetEnableAuthentication() { public void assertGetEnableAuthentication() {
Assert.isTrue(AuthUtil.ENABLE_AUTHENTICATION); Assert.isTrue(AuthUtil.isEnableAuthentication());
} }
} }

Loading…
Cancel
Save