LoginAuthorizationFilter

處理其他API驗證,檢查JWT,並動態產生權限

檢查JWT

如果在getAuthentication檢查成功,則抓取使用者帳戶資料,動態產生權限,並將使用者Id設定到Authentication中,讓其他API可以快速取得使用者Id (EX: /userId)

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader(Config.HEADER);
        System.out.println("LoginAuthorizationFilter doFilterInternal header: " + header);
        if(header == null || !header.startsWith(Config.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(Config.HEADER);
        System.out.println("LoginAuthorizationFilter getAuthentication token: " + token);
        if (token != null) {
            //parser token
            String account = Jwts.parser()
                    .setSigningKey(Config.SECRET.getBytes())
                    .parseClaimsJws(token.replace(Config.TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();

            if (account != null) {
                System.out.println("LoginAuthorizationFilter getAuthentication account: " + account);
                LoginEntity loginEntity = loginMapper.selectMember(account);
                List<GrantedAuthority> authorities = new ArrayList<>();
                if(loginEntity.getRole1() == 1) {
                    authorities.add(new SimpleGrantedAuthority("role1"));
                }
                if(loginEntity.getRole2() == 1) {
                    authorities.add(new SimpleGrantedAuthority("role2"));
                }
                String id = loginEntity.getId();
                System.out.println("LoginAuthorizationFilter getAuthentication id: " + id);
                return new UsernamePasswordAuthenticationToken(id, null, authorities);
            }
            return null;
        }
        return null;
    }

results matching ""

    No results matching ""