spring security 引入认证、授权

添加controller,访问 http://localhost:8099/api/greeting ,页面打印:Hello world

package com.example.security.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 UserController {
    @GetMapping("/greeting")
    public String greeting(){
        return "Hello world";
    }
}

pom.xml引入

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

再访问 http://localhost:8099/api/greeting ,出现认证登录页。
通过控制台输出内容复制密码:用户名为user
Using generated security password: cbd4c0e1-28c2-49a4-9176-6883cdef7acb

配置授权:

package com.example.security.config;

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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(req-> req.mvcMatchers("/api/greeting").hasRole("ADMIN"));
    }
}

再访问 http://localhost:8099/api/greeting ,登录后也不能访问,出现403,因为没有ADMIN权限。

默认配置如下(不认证权限):

protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests((requests) -> {
            ((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)requests.anyRequest()).authenticated();
        });
        http.formLogin();
        http.httpBasic();
//        http.authorizeRequests(req-> req.mvcMatchers("/api/greeting").hasRole("ADMIN"));
    }

postman之类工具访问通过Basic Auth:
在这里插入图片描述
添加post请求的api

 @PostMapping("/addUser")
 public String addUser(){
     return "Add User";
 }

访问出现403,因为post请求有csrf验证,临时关闭disable(前后端分离情况下通过token获取密串解决)

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests((requests) -> {
        ((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)requests.anyRequest()).authenticated();
    });
    http.formLogin();
    http.httpBasic();
    http.csrf(csrf->csrf.disable());
//        http.authorizeRequests(req-> req.mvcMatchers("/api/greeting").hasRole("ADMIN"));
}

默认密码

server:
  port: 8099

spring:
  security:
    user:
      name: user
      password: 12345678
      roles: USER,ADMIN

debug模式
@EnableWebSecurity(debug = true)

定时登录页:
csrf、rememberMe放到cookie或者session

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值