SPRINGBOOT 第十章

文章介绍了如何在项目中使用SpringSecurity进行安全配置,包括通过配置文件或内存配置用户信息,使用BCryptPasswordEncoder加密密码,以及添加方法安全注解。同时,文章详细展示了基于JSON的数据库安全认证实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Security

POM加入springsecurity依赖,任何接口都被保护起来了,用户及密码是每次访问随机生成的

手工配置用户名及口令,可以在数据库里面配置或在配置文件里面配置

第一种:配置文件

spring.security.user.password=123

spring.security.user.name=gcmax

spring.security.user.roles=admin

第二种:securityconfg extends websecurityConfigurerAdapter

configure

内存里面配置

密码加密

BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();

encoder.encode("123");

PasswordEncoder passwordEncoder(){

    return NoOpPasswordEncoder.getInstance();, 这里改成return new BCryptPasswordEncoder();

}

方法安全

方法上面加上注解

@PreAuthorize("hasRole('admin')")

public String admin(){

     return "hello admin";
}

@Secured("ROLB_user")

public String user(){

    return "hello user";

}

基于数据库安全认证

security-josn

 @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            //说明用户以 JSON 的形式传递的参数

            String username = null;
            String password = null;
            try {
                Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                username = map.get("username");
                password = map.get("password");
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (username == null) {
                username = "";
            }

            if (password == null) {
                password = "";
            }

            username = username.trim();

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username, password);

            // Allow subclasses to set the "details" property
            setDetails(request, authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request, response);

    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值