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

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Boot集成JWT進行身份驗證

發布時間:2024-11-15 12:06:13 來源:億速云 閱讀:91 作者:小樊 欄目:編程語言

在Spring Boot中集成JWT(JSON Web Token)進行身份驗證是一個常見的需求。以下是一個基本的步驟指南,幫助你實現這一功能。

1. 添加依賴

首先,在你的pom.xml文件中添加必要的依賴:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Starter Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- JWT -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-api</artifactId>
        <version>0.11.2</version>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-impl</artifactId>
        <version>0.11.2</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-jackson</artifactId>
        <version>0.11.2</version>
        <scope>runtime</scope>
    </dependency>

    <!-- Other dependencies -->
</dependencies>

2. 配置JWT過濾器

創建一個JWT過濾器來處理JWT的驗證和生成。

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

public class JwtRequestFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;
    private final String secretKey = "yourSecretKey"; // Replace with your secret key

    public JwtRequestFilter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

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

        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get
        // only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                Claims claims = Jwts.parser().setSigningKey(Base64.getDecoder().decode(secretKey)).parseClaimsJws(jwtToken).getBody();
                username = claims.getSubject();
            } catch (Exception e) {
                // handle exception
            }
        }

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

            if (!jwtToken.equals(Jwts.builder().setSubject(userDetails.getUsername()).signWith(io.jsonwebtoken.SignatureAlgorithm.HS256, secretKey).compact())) {
                // handle unauthorized access
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
                return;
            }
        }

        filterChain.doFilter(request, response);
    }
}

3. 配置Spring Security

配置Spring Security以使用JWT過濾器。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add JWT filter
        http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Configure user details service
        auth.userDetailsService(userDetailsServiceBean()).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtRequestFilter jwtRequestFilter() {
        return new JwtRequestFilter();
    }

    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        // Implement your UserDetailsService here
        return new CustomUserDetailsService();
    }
}

4. 實現UserDetailsService

實現一個UserDetailsService來加載用戶信息。

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // Implement your logic to load user details from database
        // For example:
        return new User(username, "password", new ArrayList<>());
    }
}

5. 生成JWT令牌

創建一個控制器來生成JWT令牌。

import io.jsonwebtoken.Jwts;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JwtController {

    private final String secretKey = "yourSecretKey"; // Replace with your secret key

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        // Implement your logic to authenticate user
        if ("user".equals(username) && "password".equals(password)) {
            return Jwts.builder()
                    .setSubject(username)
                    .signWith(io.jsonwebtoken.SignatureAlgorithm.HS256, secretKey)
                    .compact();
        } else {
            throw new RuntimeException("Invalid username or password");
        }
    }
}

總結

以上步驟涵蓋了在Spring Boot中集成JWT進行身份驗證的基本流程。你需要根據實際需求調整代碼,例如實現真正的用戶認證邏輯、處理異常等。希望這些信息對你有所幫助!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

固安县| 滨海县| 高邑县| 浠水县| 互助| 香河县| 嘉荫县| 监利县| 开江县| 玉树县| 南川市| 湖北省| 克东县| 天气| 东明县| 禄劝| 平度市| 佛冈县| 内黄县| 丰原市| 潞城市| 调兵山市| 安仁县| 玛纳斯县| 恩施市| 云安县| 资源县| 抚州市| 大庆市| 蒲城县| 涞源县| 连山| 隆昌县| 德江县| 鸡泽县| 巴塘县| 汤原县| 财经| 织金县| 静安区| 尖扎县|