1. 程式人生 > >You can either travel or read,but either your body or soul must be on the way.

You can either travel or read,but either your body or soul must be on the way.

一、具體操作

二、幾點補充

1、引入Jwt依賴

<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
		<dependency>
			<groupId>io.jsonwebtoken</groupId>
			<artifactId>jjwt</artifactId>
			<version>0.7.0</version>
		</dependency>

2、在filter中驗證token時,過期和非法的token都會丟擲異常,可以自定義bean繼承自BasicErrorController來進行統一的異常處理(返回給前端固定的Json內容,實際使用時和Js互動還會遇到跨域問題,要給response加上相關的請求頭)。

3、貼波自己寫的程式碼

注:基於 boot 1.X, 2.X的BasicErrorController有所不同

不懂的留言

@Configuration
public class JwtConfig {

    @Bean
    public FilterRegistrationBean jwtFilter() {
        final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new JwtFilter());
        registrationBean.addUrlPatterns("/test/*");//配置對應路徑的介面使用此 filter
        return registrationBean;
    }
}
@RestController
public class MyCommonErrorController extends BasicErrorController {
    //統一處理filter丟擲的token相關的異常 返回給前端標準格式的json和裝填碼
    private static final String PATH = "/error";
    private static final String TOKEN_MISS = "Missing or invalid Authorization header";
    private static final String TOKEN_EXPIRED = "token expired";
    private static final String TOKEN_INVALID = "token invalid";
    private static final String TOKEN_ERROR = "error";

    public MyCommonErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @Override
    @RequestMapping(
            produces = {"application/json"}
    )
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        //加入跨域相關內容
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Expose-Headers", "X-Total-Count");
        response.setHeader("Access-Control-Allow-Headers", "origin, x-requested-with, x-http-method-override, content-type, Authentication, Authorization, hospital");
        response.setHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS, HEAD, PATCH");
        
        HttpStatus status = this.getStatus(request);
        Map<String, Object> errorAttributes = this.getErrorAttributes(request, true);
        String message = (String)errorAttributes.get("message");
        Map<String, Object> body = new LinkedHashMap<>(16);
        body.put("code", getCode(message));
        body.put("message", message);
        body.put("data", null);
        return new ResponseEntity(body, status);
    }

    private int getCode(String msg){
        if (TOKEN_MISS.equals(msg)){
            return -1;
        }else if (TOKEN_EXPIRED.equals(msg)){
            return -2;
        }else if (TOKEN_INVALID.equals(msg)){
            return -3;
        }else if (TOKEN_ERROR.equals(msg)){
            return -4;
        }else {
            return -5;
        }
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}
@RestController
public class TokenController {
    //登陸介面
    @PostMapping("/login")
    public Object login(@RequestBody LoginRequest loginRequest){
        //假設驗證過了使用者名稱和密碼 發token
        // Create Twt token
        return generateToken(loginRequest.getUsername());
    }

    private String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>(16);
        claims.put("sub", username);
        claims.put("created", new Date());
        return generateToken((claims));
    }
    
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims)        //payload
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 1000L))  //過期時間
                .signWith(SignatureAlgorithm.HS512, "nicai").compact();  //加密方式
    }
}
@RestController
@RequestMapping("/test")
public class TestController {
    //用於測試token的驗證
    @GetMapping("")
    public Object getTest(HttpServletRequest request){
        System.out.println(request.getAttribute("claims"));
        Map<String, String> claims = (Map<String, String>) request.getAttribute("claims");
        return "test"; 
    }
}
@Data
public class TokenException extends Exception {
    //自定義異常型別
    private int code;
    private String msg;

    public TokenException() {
    }

    public TokenException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }
}
public class JwtFilter extends GenericFilterBean{
    //Jwtconfig中配置的filter 用於Jwt token的驗證工作 配置時可以指定對應的路徑
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authHeader = request.getHeader("Authorization");

        //規避探測性質的 OPTIONS請求
        String optionsString = "OPTIONS";
        String bearerString = "Bearer ";
        if (optionsString.equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //驗證token
            if (StringUtils.isEmpty(authHeader) || !authHeader.startsWith(bearerString)){
                    throw new ServletException(new TokenException(-1, "Missing or invalid Authorization header"));
            }else {
                String token = authHeader.substring(bearerString.length());
                try {
                    //使用jwt paser來驗證簽名
                    Claims claims = Jwts.parser().setSigningKey("nicai").parseClaimsJws(token).getBody();
                    request.setAttribute("claims", claims);
                }catch (ExpiredJwtException e){
                    throw new ServletException(new TokenException(-2, "token expired"));
                }catch (SignatureException e){
                    throw new ServletException(new TokenException(-3, "token invalid"));
                }catch (Exception e){
                    throw new ServletException(new TokenException(-4, "error"));
                }

            }
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

}






相關推薦

You can either travel or read,but either your body or soul must be on the way.

一、具體操作二、幾點補充1、引入Jwt依賴<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt --> <dependency> <groupId>io.json

docker升級後提示賬戶不被允許使用docker的情況:You are not allowed to use Docker. You must be in the...

設定使用者組許可權 即可: 第一步: powershell輸入如下指令: C:\WINDOWS\system32\compmgmt.msc 選擇docker-users,然後雙擊: 然後選擇新增按鈕: 選擇高階: 然後立即查詢,再搜尋結果中,選中自己的登陸

git沖突Please move or remove them before you can merge

box ng- 解決 track move 忽略文件 har mod http 解決Git沖突造成的Please move or remove them before you can merge git clean -d -fx ""其中x -----刪除忽略文件已經對

git 提示 Please move or remove them before you can merge 解決辦法

解決 如果 慎用 ase 強制 bsp rem 刪除 for 解決Git沖突造成的Please move or remove them before you can merge git clean -d -fx其中x -----刪除忽略文件已經對git來說不識別的文件d -

Git沖突:commit your changes or stash them before you can merge. 解決辦法(轉載)

顯示 file abort 轉載 win htm 內容 class 也說 用git pull來更新代碼的時候,遇到了下面的問題: error: Your local changes to the following files would be overwritten b

Please move or remove them before you can merge

目錄 地址 提交 識別 遇到 bsp 命令 lease for 在使用git pull時,經常會遇到報錯: Please move or remove them before you can merge 這是因為本地有修改,與雲端別人提交的修改沖突,又沒有merge.

If ngModel is used within a form tag, either the name attribute must be set or the form contro

背景:angular中使用form表單時報錯。 報錯資訊:If ngModel is used within a form tag, either the name attribute must be set or the form control must b

pyspark 用fit訓練資料集的時候出現"Params must be either a param map or a list/tuple of param maps, "

在anaconda用決策樹訓練資料, from pyspark.ml.classification import DecisionTreeClassifier dt=DecisionTreeClassifier(labelCol="label",features

codis擴容報錯:[error] READONLY You can't write against a read only slave

現象:最近在做codis線上擴容時,新增多組group,每個group新增一個redis作為master,當進行auto balance或手動遷移slot時,發現要遷移的slot的狀態處於error狀態,並且一直阻塞後面要遷移的slot,最終導致proxy掛掉,無法對外提供

How can you best eliminate bias when conducting a usability testing analysis or a user inquiry /…

Let’s start at the beginning with a definition of bias. The Merriam-Webster says it is:“[a] systematic error introduced into sampling or testing by selecti

Why You Can’t Help But Act Your Age

This story is for Medium members.Continue with FacebookContinue with GoogleMedium curates expert stories from leading publishers exclusively for members (w

Five Ways You Can Start Localizing Design or Product

Everybody talks about localization (or globalization, depending on how you see it). I would actually prefer to say it designing or planning with local cont

The Most Fun (and Useful) Things You Can Do With an Amazon Echo or Google Home

This story is for Medium members.Continue with FacebookContinue with GoogleMedium curates expert stories from leading publishers exclusively for members (w

【liangge的專欄】You can fool all the people some of the time, and some of the people all the time, but you cannot fool all the peopl

You can fool all the people some of the time, and some of the people all the time, but you cannot fo...

報錯:keep must be either "first", "last" or False

原因 series mac std frame col nbsp spa div data_mac_set = data_mac.drop_duplicates([‘std_mac‘]) 此時會報錯:keep must be either "first", "last"

Git更新本地衝突:commit your changes or stash them before you can merge。。。

  從github倉庫pull原始碼到本地時,提示本地衝突錯誤。   英文閱讀水平還ok,通過萬能的有道翻譯如下:“錯誤:您對以下檔案的本地更改將被合併覆蓋,請在你可以合併之前,提交你的修改或者隱

git常見問題之:commit your changes or stash them before you can merge

用git pull來更新程式碼的時候,遇到了下面的問題: error: Your local changes to the following files would be overwritten by merge: xxx/xxx/xxx

Git衝突:commit your changes or stash them before you can merge.

轉自:http://blog.csdn.net/lincyang/article/details/21519333 今天用git pull來更新程式碼,遇到了下面的問題: error: Your local changes to the following fi

Git衝突:commit your changes or stash them before you can merge. 解決辦法

用git pull來更新程式碼的時候,遇到了下面的問題:1234error: Your local changes to the following files would be overwritten by merge:           ****************

idea中使用git提交程式碼報錯:commit your changes or stash them before you can merge.

今天用git pull來更新程式碼,報了下面的錯 error: Your local changes to the following files would be overwritten by merge:      xxx/xxx/xxx.java  Plea