Spring Security

1、概述

Spring Security是Spring 的企业应用系统提供的用于用户登录和认证的一个框架。简单来说,Spring Security就是先验证是否存在该用户,然后看用户是否拥有某个权限。

2、快速入门

2.1 创建项目

a5b971bd635d4717b6f54aa0b1162d8f.png

2.2 添加依赖

90951b4e3b1541f39b4402e16bda4df2.png2.3 访问测试

首先,启动Application项目后,你的控制台会出现如下提示,注意:每次生成的密码不一样,在登录测试的时候注意密码,密码是加密后的密码。

a882fe33fa7f4e1fbfee9b357f108cb2.png

然后,访问网址 http://localhost:8080/login 进行访问测试,会跳转到如下页面,然后输入默认用户名user,密码是启动后的提示如上所示。

8bc1f1f4de1d4d7884267848f30183bb.png

最后,输入用户名和密码后,你将看到如下页面。

eeba8a4c9e7444c0af3ec05923c9f250.png

3、自定义配置

3.1 编写SecurityConfig配置类

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.context.annotation.Configuration;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/public/**").permitAll()//公开接口
                .anyRequest().authenticated()//其他接口需要登录
                .and()
                .formLogin()
                .defaultSuccessUrl("/api/private")
                .permitAll()//允许所有用户登录
                .and()
                .logout()
                .permitAll();
    }
}


3.2 定义Controller类,在Controller类中编写测试代码

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class TestController {
    @GetMapping("/public/hello")
    public String test() {
        return "hello public";
    }

    @GetMapping("/private/hello")
    public String test2() {
        return "hello private";
    }
}

3.3 启动服务,访问测试

启动服务后,访问地址 http://localhost:8080/api/public/hello ,正确结果是你能够直接跳转到页面显示 hello public;访问地址 http://localhost:8080/api/private/hello ,正确结果是当你访问该地址的时候,它会先跳转到 http://localhost:8080/login 让你进行登录,登录成功后会跳转到页面显示 hello private

4、自定义登录页面

4.1 编写登录页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<div class="login-form">
    <form action="/auth/login" method="post">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required>
        <button type="submit">登录</button>
    </form>
</div>
</body>
</html>

4.2 

  • 19
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值