springboot的security使用

本文介绍了SpringBoot集成Security框架进行安全控制的实践,特别是如何配置自定义登录页面及其'login'请求处理。

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


springboot的security使用


package com.lishao.config;

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.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                //路由为/的允许所有人都能访问首页为/
                .antMatchers("/").permitAll()
                //功能页面就得有权限的人才能进
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //
        http.csrf().disable();
        //没有认证会跳转到登录页面
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
        //注销  退出登录
        http.logout().logoutSuccessUrl("/");
        //记住我  是存在cok中的
        http.rememberMe().rememberMeParameter("remember");


    }
    //认证
//.passwordEncoder(new BCryptPasswordEncoder()) 为密码编码
    //inMemoryAuthentication为获取内存中的
    //roles权限
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lishao").password(new BCryptPasswordEncoder()
                .encode("asdasd"))
                .roles("vip1")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder()
                .encode("root"))
                .roles("vip1","vip2","vip3");
    }
}

在这里插入图片描述
登陆页面要写login这个请求
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值