基于Spring boot + SpringSecurity 的FormLogin模式实现 (二)

基于Spring boot + SpringSecurity 的FormLogin模式实现 (二)

基于Spring boot + SpringSecurity第二部分

1. 下面我们开始使用FormLogin模式,具体步骤:1.编写login.html
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.12.3/jquery.min.js" ></script>
</head>
<body>
<h1>Friday权限管理系统</h1>
<form action="/login" method="post">
    <span>用户名称:</span> <input type="text" name="username" id="username"/> <br>
    <span>用户密码:</span><input type="text" name="password" id="password"/> <br>
    <input type="button" onclick="login()" value="登录"/>
</form>
</body>

2.创建一个继承WebSecurityConfigurerAdapter的SecurityConfig类,重
写configure(HttpSecurity http) 方法,用来配置登录验证逻辑。

package com.example.security1.config.security;

import com.example.security1.config.security.handler.MyAuthenticationFailureHandler;
import com.example.security1.config.security.handler.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
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 javax.annotation.Resource;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Resource
    MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                    .formLogin() //开启formLogin模式
                    .loginPage("/login.html") //用户未登录时,访问任何资源都跳转到该路径,即登录页面
                    .loginProcessingUrl("/login") //登录表单form中action的地址,也就是小狐狸认证请求的路径
                    .usernameParameter("username") //默认是username
                    .passwordParameter("password") //默认是password
//                    .defaultSuccessUrl("/index") //登录成功跳转接口
//                    .failureUrl("/login.html") //登录失败跳转的页面
                    .successHandler(myAuthenticationSuccessHandler)
                    .failureHandler(myAuthenticationFailureHandler)
                    .and() //使用and()连接
                    .authorizeRequests() //配置权限
                    .antMatchers("/login.html","/login")
                    .permitAll() //用户可以任意访问
                    .antMatchers("/order") //需要对外暴露的资源路径
                    .hasAnyAuthority("ROLE_user","ROLE_admin") //user角色和admin角色都可以访问
                    .antMatchers("/system/user","/system/role","/system/menu")
                    .hasAnyRole("admin") //admin角色可以访问
                    .anyRequest().authenticated() //authenticated()需要在执行该请求时,必须已经登录了应用
                    .and()
                    .csrf().disable(); //禁用跨站csrf攻击防御,否则无法登录成功
        //登出功能
        httpSecurity.logout().logoutUrl("/logout");

    }
}

上图代码分三段理解:
1.配置认证,开启formLogin模式;
2.配置权限;
3.禁用跨站csrf攻击防御。

/**
* anyRequest | 匹配所有请求路径
* access | SpringEl表达式结果为true时可以访问
* anonymous | 匿名可以访问
* denyAll | 用户不能访问
* fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登
录)
* hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限
可以访问
* hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色
可以访问
* hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
* hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数
匹配,则可以访问
* hasRole | 如果有参数,参数表示角色,则其角色可以访问
* permitAll | 用户可以任意访问
* rememberMe | 允许通过remember-me登录的用户访问
* authenticated | 用户登录后可访问
*/

3.这里我们采用内存中身份认证的方法,在SecurityConfig类重写
configure(AuthenticationManagerBuilder auth)方法,增加user和
admin两个用户的配置,后续我们会根据RBAC模型设计数据表,实现基于数
据库动态的配置。

官方推荐使用 BCryptPasswordEncoder 进行密码加密。
bcrypt 是一种跨平台的文件加密工具。bcrypt 使用的是布鲁斯·施内尔在1993年发布
Blowfish 加密算法。由它加密的文件可在所有支持的操作系统和处理器上进行转
移。它的口令必须是8至56个字符,并将在内部被转化为448位的密钥

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password(bCryptPasswordEncoder().encode("123456"))
                .roles("user")
                .and()
                .withUser("admin")
                .password(bCryptPasswordEncoder().encode("123456"))
                .roles("admin")
                .and()
                .passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

4.运行验证,使用浏览器访问:http://localhost:8080。
在这里插入图片描述
在username中输入user,password输入123456,点击登录按钮,我们可以成功登录到
系统中。
在这里插入图片描述
根据权限配置,user用户可以访问订单页面,不能访问用户管理、角色管理和菜单管理,


下面我们分别访问订单页面和用户管理页面,看一下是不是和我们的代码配置一致。


5.一行代码实现登出功能。


Spring Security帮我们实现登出功能的大部分代码,我们只需要在
configure(HttpSecurity httpSecurity)方法内添加一行即可:


点击订单页面,可以正常访问:

在这里插入图片描述


点击用户管理页面,提示我们被禁止访问:


在这里插入图片描述
5.一行代码实现登出功能。
Spring Security帮我们实现登出功能的大部分代码,我们只需要在
configure(HttpSecurity httpSecurity)方法内添加一行即可:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值