2021-2-23 SpringSecurity (一)

maven 引入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

SecurityConfig

package com.qizhi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Security配置类
 *
 * @author qizhi on 2021/2/23
 * @since 1.0.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //表单登录
        http.formLogin()
                //登录的页面
                .loginPage("/login.html")

                //执行登录逻辑的controller
                .loginProcessingUrl("/login")

                //登陆成功 页面重定向其他页面    //此路径需要是 post请求   //可以自定义一个登陆成功后 用get请求跳转的地址  这两个不能一块用
                .successForwardUrl("/tologin")

                //自定义错误跳转
                .failureHandler(new AuthenticationFailtureHandler("https://www.baidu.com/"));

                //必须为post请求  失败跳转页面
//                .failureForwardUrl("toError");

                //自定义参数名
//                .usernameParameter("")

        //授权
        http.authorizeRequests()
                .antMatchers("/login.html").permitAll()
                //所有请求都需要被认证才能访问
                .anyRequest().authenticated();

        //关闭csrf防护  相当于防火墙
        http.csrf().disable();
    }
}

http.formLogin() 链式编程

form登录设置

所有的表单跳转都是post请求

//表单登录
        http.formLogin()
                //登录的页面
                .loginPage("/login.html")

                //执行登录逻辑的controller
                .loginProcessingUrl("/login")

                //登陆成功 页面重定向其他页面    //此路径需要是 post请求   //可以自定义一个登陆成功后 用get请求跳转的地址  这两个不能一块用
                .successForwardUrl("/tologin")

                //自定义错误跳转
                .failureHandler(new AuthenticationFailtureHandler("https://www.baidu.com/"));

                //必须为post请求  失败跳转页面
//                .failureForwardUrl("toError");

                //自定义参数名
//                .usernameParameter("")

自定义跳转请求设置为get方式

.failureHandler(
new AuthenticationFailtureHandler(
"https://www.baidu.com/"));

new AuthenticationFailtureHandler 自定义的跳转类

package com.qizhi.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

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

/**
 * 自定义登陆失败跳转
 *
 * @author qizhi on 2021/2/23
 * @since 1.0.0
 */
public class AuthenticationFailtureHandler implements AuthenticationFailureHandler {

    private final String forwardUrl;

    /**
     * @param forwardUrl
     */
    public AuthenticationFailtureHandler(String forwardUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl),
                () -> "'" + forwardUrl + "' is not a valid forward URL");
        this.forwardUrl = forwardUrl;
    }
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.sendRedirect(forwardUrl);
    }
}

页面拦截

http.authorizeRequests()

需要关闭防火墙否则登录操作进入不了

http.csrf().disable();

http.authorizeRequests()
                //表示匹配的路径资源允许放行
                .antMatchers("/login.html").permitAll()
                //所有请求都需要被认证才能访问
                .anyRequest().authenticated();

        //关闭csrf防护  相当于防火墙
        http.csrf().disable();

UserDetails

UserDetails 内部字段 表示 用户登录必须含有的 且带有的

UserDetailsService 登录必须要实现的接口 返回 UserDetails
实现loadUserByUsername()方法

UserDetails 表示用户内部信息,如果还有其他字段需要放入 可创建自己的用户表 并实现此UserDetails 接口

内置了User 对象 来接受认证信息 也可以自定义用户类

AuthorityUtils.commaSeparatedStringToAuthorityList(“admin,normal”) 表示赋予此用户什么权限

  @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据username查询数据库

        System.out.println("执行登陆操作");
        if(!"admin".equals(username)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //2.比较密码
        String password = passwordEncoder.encode("123456");
        //3.返回用户数据
        return new User("admin",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));
    }

密码需要加密才能通过登陆操作 需要注入一个 编码器 俗称加密类一般放入SecurityConfig类中

 @Bean
   public PasswordEncoder passwordEncoder(){
       return new BCryptPasswordEncoder();
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大大陈·

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

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

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

打赏作者

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

抵扣说明:

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

余额充值