中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

SpringBoot結合JWT怎么實現用戶登錄功能

小億
95
2024-01-24 12:25:47
欄目: 編程語言

要實現SpringBoot結合JWT實現用戶登錄功能,可以按照以下步驟進行操作:

  1. 添加相關依賴:在pom.xml文件中添加Spring Security和JWT的依賴。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
  1. 創建用戶實體:創建一個用戶實體類,包含用戶名和密碼等屬性。
public class User {
    private String username;
    private String password;

    // getter and setter
}
  1. 創建用戶認證服務:創建一個實現UserDetailsService接口的用戶認證服務類,用于加載用戶信息。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 從數據庫或其他數據源加載用戶信息
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
    }
}
  1. 創建登錄控制器:創建一個登錄控制器類,用于處理用戶登錄請求。
@RestController
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
            String token = jwtUtils.generateToken(user.getUsername());
            return ResponseEntity.ok(token);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }
}
  1. 創建JWT工具類:創建一個JWT工具類,用于生成和解析JWT。
@Component
public class JwtUtils {

    private final String secret = "your-secret-key";
    private final long expiration = 86400000;

    public String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public String getUsernameFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    public boolean isTokenValid(String token, UserDetails userDetails) {
        String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }

    private boolean isTokenExpired(String token) {
        Date expirationDate = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody()
                .getExpiration();
        return expirationDate.before(new Date());
    }
}
  1. 配置Spring Security:在application.properties文件中配置Spring Security的相關屬性。
spring.security.user.name=admin
spring.security.user.password=admin
spring.security.user.roles=USER,ADMIN
  1. 配置JWT過濾器:創建一個JWT過濾器類,用于驗證請求中的JWT并在Security上下文中設置認證信息。
@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader("Authorization");

        if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            String username = jwtUtils.getUsernameFromToken(token);

            if (StringUtils.hasText(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                if (jwtUtils.isTokenValid(token, userDetails)) {
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}
  1. 配置Spring Security

0
红桥区| 塔城市| 庆元县| 德令哈市| 大荔县| 咸丰县| 河北区| 东港市| 祥云县| 石柱| 介休市| 尼勒克县| 商丘市| 保山市| 太和县| 同德县| 来宾市| 彭山县| 宜兰市| 新宾| 方山县| 邳州市| 涞水县| 永和县| 镶黄旗| 焉耆| 二连浩特市| 承德市| 宽城| 礼泉县| 商洛市| 舞阳县| 华阴市| 皋兰县| 湖州市| 如东县| 苗栗市| 翼城县| 南雄市| 武安市| 红安县|