LDAP域单点登录认证并生成JWT

一、POM文件添加以下依赖

<!-- LDAP 单点登录-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-ldap</artifactId>
</dependency>
<!-- JWT -->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

解释:

1、spring-boot-starter-security

用于Spring Security的基础配置。

2、spring-boot-starter-date-ldap

用于与LDAP服务器的交互。

3、spring-ldap-core和spring-security-ldap

实现LDAP认证的核心组件。

4、jjwt

用于生成和验证JWT

二、配置Spring Security

package com.example.ssonothing01.Config;

//import com.example.ssonothing01.security.JwtFilter;

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.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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/login").permitAll()  // 允许匿名访问 /api/login
                .anyRequest().authenticated();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("登录动作抓捕:2");
        auth.ldapAuthentication()
                .userSearchBase("ou=Software Development,ou=Mobile Product Development,ou=Tech")
                .userSearchFilter("(sAMAccountName={0})").contextSource()
                .url("ldap://172.30.60.1:3268/dc=noth,dc=local")
                .managerDn("CN=ldapfordev,OU=Tech,dc=noth,dc=local")
                .managerPassword("******");
    }

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

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

}

解析:
配置CORS和CSRF,设置允许匿名访问登录接口/api/login,其他接口需要认证。
通过AuthenticationManagerBuilder配置LDAP认证,定义LDAP服务器地址、用户搜索路径和凭证。

三、实现认证逻辑与生成JWT

package com.example.ssonothing01.Controller;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/api")
public class AuthController {

    private final AuthenticationManager authenticationManager;

    @Autowired
    public AuthController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/login")
    public ResponseEntity<JSONObject> login(@RequestBody LoginRequest loginRequest) {
        System.out.println("LoginRequest:"+loginRequest.getUsername() + "," + loginRequest.getPassword());
        JSONObject resultJson = new JSONObject();
        //LDAP域服务器验证,如果用户验证不通过,在这一步就会抛出异常
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        //生成用户Token,由于接口调用验证,和定期校验身份
        String token = Jwts.builder()
                .setSubject(authentication.getName())
                .setExpiration(new Date(System.currentTimeMillis() + 864000000))  // 10天有效期
                .signWith(SignatureAlgorithm.HS512, "secret".getBytes())
                .compact();
        resultJson.put("status", true);
        resultJson.put("token", token);
        System.out.println("token:"+token);
        return new ResponseEntity<>(resultJson, HttpStatus.OK);
    }

}

package com.example.ssonothing01.security;

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.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
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.Collections;

@Component
public class JwtFilter extends OncePerRequestFilter {

    private final String secretKey = "secret"; // 请使用更安全的密钥

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 跳过 /api/login 请求
        if ("/api/login".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }

        String authorizationHeader = request.getHeader("Authorization");
        String token;
        String username = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring(7);
            try {
                Claims claims = Jwts.parser()
                        .setSigningKey(secretKey.getBytes())
                        .parseClaimsJws(token)
                        .getBody();
                username = claims.getSubject();
            } catch (Exception e) {
                // 处理令牌解析异常
            }
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    username, null, Collections.emptyList());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
package com.example.ssonothing01.Controller;
import lombok.Data;

@Data
public class LoginRequest {
    private String username;

    private String password;
}

用户发送POST请求到/api/login,携带LDAP用户名和密码,使用authenticationManager.authenticate方法执行LDAP认证,认证通过则生成JWT(有效期10天,并使用HS512算法签名)

四、结论

1、LDAP认证配置

使用Spring Security和LDAP依赖,项目通过LDAP实现用户认证,指定LDAP服务器、用户搜索路径和管路员凭证进行验证。

2、JWT生成

认证成功后,生成JWT令牌,包含用户身份信息,设置了10天的有效期。该令牌可以应用于后续的API请求认证。

3、安全配置

项目允许匿名访问/api/login登录接口,而其他接口需要通过JWT进行身份认证,确保安全性。

五、优点

1、简洁且有效的配置

项目使用了Spring Security和LDAP提供的标准机制,实现了LDAP单点登录的认证,代码简洁明了。Spring Security和Spring LDAP整合良好,简化了LDAP认证的实现过程。

2、JWT集成便捷

通过io.jsonwebtoken库(jjwt)快速集成了JWT,认证成功后生成Token用于后续的身份验证,减少了每次请求都与LDAP服务器交互的负载。

3、配置灵活性

配置了用户搜索路径、LDAP服务器URL、管理员凭证等,具有较好的灵活性,适应不同的LDAP服务器结构。

4、增强安全性

禁用了CSRF波阿虎,适合无状态的API认证模式(通过JWT),并限制除了登录以外的所有接口都需要经过认证,这符合RESTful API设计的最佳实践。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Senye_ing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值