SpringBoot与spring security的结合的示例

网友投稿 249 2023-02-11


SpringBoot与spring security的结合的示例

权限控制,也是我们再日常开发中经常遇到的场景,需要根据用户的角色决定是否可以看到某个资源。目前,市面上此类框架主要有shiro与我们今天要讲到的spring securiCRchYiECbty。关于权限的控制有复杂的控制,例如几乎每个公司都有单点登录系统,根据用户名来到数据库中拿到对应的权限,在展示该权限下能看到的资源。还有一种就是简单的控制,也就是我们今天所要提到的。将账号,密码,角色配置到代码中,也可以进行简单的控制,缺点不言而喻,扩展性不好,只有固定的账号,但是作为演示还是够用的。

好了废话不多说,上pom

org.springframework.boot

spring-boCRchYiECbot-starter

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-security

spring-boot-starter-security里面包装了spring security所需要的依赖。不需要我们一个个的配置,简化了我们的操作,节省了我们的时间,不得不说,这些企业级框架考虑的就是很周到,如果我们自己添加jar,可能会因为版本之间的不兼容而爆出各种问题,这都是题外话,赞叹一下,我们继续。看下配置类

package com.shuqi;

import org.springframework.context.annotation.Configuration;

import org.springframework.core.annotation.Order;

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 {

@Configuration

public static class WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

@Override

protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable();

http

.authorizeRequests()

.antMatchers(

"/index"

).hasRole("ADMIN")

.anyRequest().permitAll()

.and()

.httpBasic()

;

}

}

}

这段配置翻译成中文是:对于访问/index这个链接需要ADMIN权限,其他的全都都允许。有的时候我们只会注意代码,其实这个注解@EnableWebSecurity会重要更多,因为他是spring security的开始,他引入了诸多的配置类,才使得security生效。我们设置了ADMIN权限,但是没有设置ADMIN权限对应的用户名密码,所以看下配置文件

security:

user:

name: root

password: root

role: ADMIN

配置都差不多了,看一眼我们的Controller

package com.shuqi.controller;

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

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

@RestController

public class HelloController {

@RequestMapping("/index")

public String index(){

return "hello world index";

}

@RequestMapping("/index1")

public String index1(){

http:// return "hello world index1";

}

}

一个被拦截的/index,一个不会被拦截的/index1,看下区别。启动项目,访问/index

可以看到已经加了访问控制,输入配置的root,root

可以看到结果

输入/index1可以直接看到结果

说明我们的配置生效了,spring security确实帮助我们做到了访问的控制。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Eclipse配置使用web.xml的方法
下一篇:关于在线http接口测试的信息
相关文章

 发表评论

暂时没有评论,来抢沙发吧~