91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
建平县| 江城| 武冈市| 赤峰市| 德钦县| 常州市| 茶陵县| 甘肃省| 油尖旺区| 定远县| 乐都县| 巴彦县| 外汇| 洛浦县| 宝丰县| 新余市| 竹北市| 原阳县| 常州市| 清丰县| 镇江市| 育儿| 武隆县| 西充县| 兴仁县| 筠连县| 南江县| 桐城市| 贵州省| 河源市| 禹城市| 福建省| 扶绥县| 株洲市| 武平县| 辉南县| 昆山市| 霍林郭勒市| 抚宁县| 英吉沙县| 西林县|