springboot学习记录之 spring security简单使用

本文记录了博主学习spring security(以下称为security)的过程,并整理了相关细节。

1.创建项目

导入maven依赖包:

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

创建项目的话就不在此篇章介绍了。

2.编写页面及控制器

来编写一个返回页面的Controller和一个简单的html页面

HelloSecurityController.java

@Controller
@RequestMapping
public class HelloSecurityController {
    @RequestMapping("/hello")
    public String toHelloSecurityPage() {
        return "hellosecurity";
    }
}

hellosecurity.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HelloSecurity</title>
</head>
<body>
HelloSecurity!HelloSecurity!HelloSecurity!
</body>
</html>

访问localhost:8080/hello,成功



3.导入spring security

首先导入Maven依赖:此包一旦导入,默认开启security,因此为了对比没在开头导入此包!

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

再次访问localhost:8080/hello ,此链接被重定向为localhost:8080/login,这是security默认的login页面。


4.配置spring security

使用@Configuration注解来开启springboot配置,@EnableWebSecurity注解来开启Security配置

并继承一个叫WebSecurityConfigurerAdapter的类,重写其中的方法,并注入账户。

@Configuration
@EnableWebSecurity //开启Security之后我们要继承一个叫WebSecurityConfigurerAdapter的类
public class MySecurityConfig extends WebSecurityConfigurerAdapter {


    //重写其中的configure参数是HttpSecurity类型的方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }

   @Autowired
   public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
       // security5  密码增加了校验方式 往内存中加入一个用户 不区分大小写
       auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user").
               password(new BCryptPasswordEncoder().encode("123")).roles("USER");
       //可以加入多个用户
       auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("userCopy").
               password(new BCryptPasswordEncoder().encode("123")).roles("USER");
   }
}

这样我们再次访问localhost:8080/hello,因为为验证授权,同样来到login页面

先输入错误密码 ,验证未通过

输入对的密码,直接跳转到hello页面

访问localhost:8080/login?logout,成功退出

5.修改默认login页面

在这之前,我们先将默认login页面的源代码复制一份,一会儿贴到我们自己的login页面(右键查看源代码或者开发者工具取代码)

在这先贴一份我复制出来的源代码 ,csrf暂不做研究

<html>
<head><title>Login Page</title></head>
<body οnlοad='document.f.username.focus();'>
<h3>Login with Username and Password</h3>
<form name='f' action='/login' method='POST'>
    <table>
        <tr>
            <td>User:</td>
            <td><input type='text' name='username' value=''></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type='password' name='password'/></td>
        </tr>
        <tr>
            <td colspan='2'><input name="submit" type="submit" value="Login"/></td>
        </tr>
        <input name="_csrf" type="hidden" value="e2abb82b-9492-492c-bdc7-038cd38973df"/>
    </table>
</form>
</body>
</html>

可以看到是form表单提交,我们将此表单领出来改成自己的login页面,并在MySecurityConfig中配置。

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>My Login Page</title>
</head>
<body>
<form th:action="@{/login}" method='POST'>
    <table>
        <tr>
            <td>User:</td>
            <td><input type='text' name='username' value=''></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type='password' name='password'/></td>
        </tr>
        <tr>
            <td colspan='2'><input name="submit" type="submit" value="Login"/></td>
        </tr>
    </table>
</form>
</body>
</html>

修改hellosecurity.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HelloSecurity</title>
</head>
<body>
HelloSecurity!HelloSecurity!HelloSecurity!
<a th:href="@{/login?logout}">退出</a>
</body>
</html>

在HelloSecurityController增加方法

 @RequestMapping("/login")
    public String toLoginPage() {
        return "login";
    }

在MySecurityConfig修改方法

  protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
                antMatchers("/**").authenticated() //对所有请求进行验证
                .and()
                .formLogin().loginPage("/login").permitAll() //指向我们的login页面 成功后请求/hello permitAll()方法表示不验证
                .defaultSuccessUrl("/hello")
                .and()
                .logout().logoutSuccessUrl("/login").permitAll();
    }

访问localhost:8080/hello,得到我们自己的页面


输入账号,密码,成功跳转


点击退出,成功退出



自此,简单的security已经完成

需要demo的可以点击 下载


下篇介绍对自定义用户的处理以及静态资源的处理




 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值