security放行 spirng_Spring Security配置

第一步,空Spring Boot环境。

暂时不添加了Spring Security依赖。

第二步,确保项目能够正常运行。

启动启动项 Application.java

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.boot.autoconfigure.SpringBootApplication;

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

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

@SpringBootApplication

@RestController

@EnableAutoConfiguration

public class AuthorityApplication {

public static void main(String[] args) {

SpringApplication.run(AuthorityApplication.class, args);

}

// localhost:8080/

@RequestMapping(value = "/")

public String home() {

return "这是根路径";

}

// localhost:8080/hello

@RequestMapping(value = "/hello")

public String hello() {

return "hello";

}

}

确保Spring Boot项目能够正常启动。

第三步,添加了Spring Security依赖。

org.springframework.bootspring-boot-starter-security

重启Application,访问 localhost:8080/ ,出现以下界面,自动跳转至 http://localhost:8080/login ,需要登录,实现了认证功能。

第四步,自定义Spring Security配置文件 SpringSecurityCustomConfig.java 。

1.实现对主路径放行、其他路径请求需要验证、注销操作允许任意权限访问、表单登录允许任意权限访问。

2.对js、css、images不做拦截。

import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.builders.WebSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration//配置文件@EnableWebSecurity//打开web支持

public class SpringSecurityCustomConfig extends WebSecurityConfigurerAdapter {@Override

protected void configure(HttpSecurity http) throws Exception {//决定那些请求被拦截

http.authorizeRequests()

.antMatchers("/").permitAll()//主路径放行

.anyRequest().authenticated()//其他请求需经过验证

.and()

.logout().permitAll()//注销操作允许任意权限访问

.and()

.formLogin().permitAll();//表单登录允许任意权限访问

http.csrf().disable();//关闭默认的csrf认证

}@Override

public void configure(WebSecurity web) throws Exception {

web.ignoring().antMatchers("/js'/**", "/css/**", "/images/**");//对js、css、images不做拦截

}

}

访问主路径 http://localhost:8080/ ,不需要验证。

访问其他路径 http://localhost:8080/hello ,需要验证。出现以下界面,自动跳转至 http://localhost:8080/login

Spring Security常见案例

案例一:只需登录

不希望花太多时间做登录功能,也不希望数据库存储登录用户名和密码。

自定义Spring Security配置文件 SpringSecurityCustomConfig.java ,通知系统在内存中有一个用户名为“admin”,用户密码为“123456”的用户,该用户角色为“ADMIN”。

访问需要验证的路径 http://localhost:8080/hello ,分别输入错误信息和正确信息。

访问 http://localhost:8080/login?logout 即可登出。

import org.springframework.context.annotation.Configuration;

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.builders.WebSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration// 配置文件

@EnableWebSecurity// 打开web支持

public class SpringSecurityCustomConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

// Spring Security提供了一套基于内存的验证

auth.inMemoryAuthentication()

.withUser("admin")

.password("123456")

.roles("ADMIN");// 自定义角色

// 可以添加若干个auth.inMemoryAuthentication()

}

@Override

protected void configure(HttpSecurity http) throws Exception {

// 决定那些请求被拦截

http

.authorizeRequests()

.antMatchers("/").permitAll()// 主路径放行

.anyRequest().authenticated()// 其他请求需经过验证

.and()

.formLogin().permitAll()// 表单登录允许任意权限访问

.and()

.logout().permitAll();// 注销操作允许任意权限访问

http.csrf().disable();// 关闭默认的csrf认证

}

@Override

public void configure(WebSecurity web) throws Exception {

web.ignoring().antMatchers("/js'/**", "/css/**", "/images/**");// 对js、css、images不做拦截

}

}

案例二:指定角色,权限按角色分配

自定义Spring Security配置文件 SpringSecurityCustomConfig.java ,通知系统在内存中有一个用户名为“caiji”,用户密码为“caiji”的用户,该用户角色为“USER”。

访问需要验证的路径 http://localhost:8080/hello

访问需要验证的路径 http://localhost:8080/roleAuth ,caiji无权限访问,admin可以访问

Application.java

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

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

import org.springframework.web.bind.annotation.RestController;@SpringBootApplication@RestController@EnableAutoConfiguration//Spring Boot会自动根据jar依赖自动配置项目@EnableGlobalMethodSecurity(prePostEnabled = true)// 启动注解@PreAuthorize的作用

public class AuthorityApplication {

public static void main(String[] args) {

SpringApplication.run(AuthorityApplication.class, args);

}// localhost:8080/

@RequestMapping(value = "/")

public String home() {return "这是根路径";

}// localhost:8080/hello@RequestMapping(value = "/hello")

public String hello() {return "hello ADMIN";

}// localhost:8080/hello@PreAuthorize("hasRole('ROLE_ADMIN')")//RoleVote中定义需要添加前缀@RequestMapping(value = "/roleAuth")

public String roleAuth() {return "hello USER";

}

}

SpringSecurityCustomConfig.jaca@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {//Spring Security提供了一套基于内存的验证

auth.inMemoryAuthentication()

.withUser("admin")

.password("123456")

.roles("ADMIN");//自定义角色//可以添加若干个auth.inMemoryAuthentication()

auth.inMemoryAuthentication().withUser("caiji").password("caiji").roles("USER");//USER用户

}

案例三:数据库管理用户

新增 UserService 类,实现 UserDetailsService 。

UserService.java

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Component;

@Component

public class UserService implements UserDetailsService {@Override

public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {returnnull;

}

}

将用户admin、caiji放入数据库,使用UserService管理。

SpringSecurityCustomConfig.java@Autowired

private UserService userService;@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {//Spring Security提供了一套基于内存的验证//auth.inMemoryAuthentication()// .withUser("admin")// .password("123456")// .roles("ADMIN");//自定义角色// //可以添加若干个auth.inMemoryAuthentication()// auth.inMemoryAuthentication().withUser("caiji").password("caiji").roles("USER");//USER用户

auth.userDetailsService(userService);

}

自定义密码管理验证,新建 PasswordCustomEncoder 类,实现 PasswordEncoder 接口。

Spring Security提供了许多对密码加密的封装类,此处以MD5加密为例。

PasswordCustomEncoder.java

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

import org.springframework.security.crypto.password.PasswordEncoder;/**

* @author tabjin* create at 2019-06-29 09:05

* @program authority* @description*/public class PasswordCustomEncoder implements PasswordEncoder {

private final static String SALT= "123456";/**

*加密方法,对原始密码加密* @paramcharSequence* @return

*/

@Override

public String encode(CharSequence charSequence) {

Md5PasswordEncoder md5PasswordEncoder=new Md5PasswordEncoder();return md5PasswordEncoder.encodePassword(charSequence.toString(), SALT);//加密并附加123456

}/**

*匹配方法,对原始密码和加密后密码匹配* @paramcharSequence* @params* @return

*/

@Override

public boolean matches(CharSequence charSequence, String s) {

Md5PasswordEncoder md5PasswordEncoder=new Md5PasswordEncoder();return md5PasswordEncoder.isPasswordValid(s, charSequence.toString(), SALT);//保证盐值和加密时一样

}

}

回到定义认证的类 SpringSecurityCustomConfig.java

SpringSecurityCustomConfig.java@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {//自定义处理

auth.userDetailsService(userService).passwordEncoder(new PasswordCustomEncoder());//指定好UserService后添加自定义密码验证器//Spring Security 默认数据库处理,表结构位于users.ddl

auth.jdbcAuthentication().usersByUsernameQuery("").passwordEncoder(new PasswordCustomEncoder());

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/349122.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Cactoos中的面向对象的声明式输入/输出

Cactoos是一个面向对象的Java原语库, 我们几周前才开始使用它。 目的是为JDK,Guava,Apache Commons等提供一种干净且更具声明性的替代方案。 我们不是使用静态过程,而是使用对象的使用方式,而是使用对象。 让我们看看输…

计算机研发部门职责,计算机研发岗位职责

计算机视觉研发员 •负责计算机视觉相关的技术研发工作,包括但不限于:人脸识别、物体检测与分类、静态图像或视频分类与分析、图像质量评价、图像处理等•负责计算机视觉方向前沿问题的研究,结合未来实际应用场景,提供技术解决方案•负责完成相关技术的研究项目申请、学术论文发…

vue中请求接口怎么封装公共地址_vue请求接口的封装

import api from ./api;import request from./request;//获取url上的rest参数,返回参数列表 /{userId}/{roleId} > [userId, roleId]functiongetUrlParams(url) {return (url.match(/\{(\w)\}/g) || []).map(param > /\{(\w)\}/.exec(param)[1]);}/** 创建一个…

java实现迷你计算机,用JAVA写一个迷你编辑器.doc

用JAVA写一个迷你编辑器用JAVA编写一个迷你编辑器WINDOWS的记事本程序是非常方便的一个文字处理工具,用它来编辑纯文本文件快捷而灵巧。我用JAVA写了一个编辑器程序,模仿“记事本”的功能。这不是为了替代记事本,而是因为下列两个目的&#x…

cypress测试脚本_Cypress 自动化测试学习使用

安装mkdir cypress-startnpm install# 进入创建的项目目录cd /your/project/pathcd cypress-startnpm install cypress --save-devyarn addcd /your/project/pathcd cypress-startyarn add cypress --dev打开运行cpress./node_modules/.bin/cypress open或者使用npm bin$(npm b…

hadoop综述_Hadoop书籍赠品–综述

hadoop综述各位极客, Packt Publishing关于Apache Hadoop 的书籍赠品已经结束。 您可以在这里找到比赛的原始帖子。 获奖者 将会获得这本书奖的6位幸运获奖者是(姓名出现在他们的电子邮件中): Hadoop真实世界解决方案食谱 塞…

便捷式计算机无线功能按钮,TP-Link TL-MR13U便携式无线路由器Client模式设置

本文介绍了TP-Link TL-MR13U便携式无线路由器,在“客户端模式(Client)”下的设置方法。TL-MR13U工作在“客户端模式(Client)”时,主要作用是用来接收无线WiFi信号,把无线WiFi信号转换为有线网络,实现让台式电脑上网。TP-Link TL-M…

Java命令行界面(第6部分):JOpt简单

JOpt Simple的主页将这个基于Java的库称为“用于解析命令行选项的Java库,例如您可能传递给调用javac的Java库,”该Java库试图“使用POSIX getopt()的命令行选项语法)和GNU getopt_long() 。” 这…

矩阵相乘的strassen算法_矩阵乘法的Strassen算法+动态规划算法(矩阵链相乘和硬币问题)...

矩阵乘法的Strassen这个算法就是在矩阵乘法中采用分治法,能够有效的提高算法的效率。先来看看咱们在高等代数中学的普通矩阵的乘法两个矩阵相乘上边这种普通求解方法的复杂度为: O(n3)也称之为暴力求解或者朴素求解这是暴力求解的代码,三重循环&#xff…

计算机c盘哪些东西可以清理,细说电脑c盘哪些文件可以删除

有些网友反映,自己看C盘里的文件太多了,电脑又太卡,情急之下就把里面的东西删掉了,现在系统都不能用了。为了避免大家再入这个坑,我给大家讲一下哪些是C盘里的无用文件,并且删除后不会影响系统使用C盘是指电…

springboot 注解动态赋值_SpringBoot 使用 @Value 注解读取配置文件给静态变量赋值

1、application.properties 配置文件CxU免费资源网mail.usernamexue163.commail.passwordxuemail.hostsmtp.163.commail.smtp.authtrue2、给普通变量赋值,直接在变量上添加 Value 注解CxU免费资源网import org.springframework.beans.factory.annotation.Value;publ…

软件测试度量计算方法有哪些,软件测试度量(三)

进度差异趋势6.4.3 范围变化(SC)这个指标指出如何固定测试范围。下面总范围 以前的范围 新范围,如果范围扩大的话总范围 以前的范围 - 新范围,如果范围缩小的话一个发布版本范围变化趋势7、结论度量是评估的重要组成部分以及任何业务改进的基础。是应…

ceph与hdfs的比较_分布式存储中HDFS与Ceph两者的区别是什么,各有什么优势?

过去两年,我的主要工作都在Hadoop这个技术栈中,而最近有幸接触到了Ceph。我觉得这是一件很幸运的事,让我有机会体验另一种大型分布式存储解决方案,可以对比出HDFS与Ceph这两种几乎完全不同的存储系统分别有哪些优缺点、适合哪些场…

使用带有OAuth的Spring Security保护资源

1.简介 在本教程中,我们将研究如何使用Spring Security和OAuth来基于路径模式( / api / ** )保护服务器上的管理资源。 我们配置的另一个路径模式( / oauth / token )将帮助已配置的授权服务器生成访问令牌。 请注意&a…

2080ti服务器支持什么系统,2080ti深度学习性能

AI开发平台ModelArtsModelArts是面向开发者的一站式AI开发平台,为机器学习与深度学习提供海量数据预处理及半自动化标注、大规模分布式Training、自动化模型生成,及端-边-云模型按需部署能力,帮助用户快速创建和部署模型,管理全周…

pythonset是什么类型的游戏_Python集合(set)类型的操作

原文详见:http://blog.csdn.net/business122/article/details/7541486python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等…

服务器选购seo优化规则,网站seo优化注意事项1—域名和服务器选择

原标题:网站seo优化注意事项1—域名和服务器选择一个网站的域名和服务器是很重要的,这关乎网站的优化前提,作为一个seo优化人员必须要对自己网站的域名和服务器有所了解。网站seo优化注意事项1:域名的关联性域名怎么选择呢&#x…

as cast float server sql_Sql Server中Float格式转换字符串varchar方法(转)

SELECT CONVERT(varchar(100), CAST(testFloat AS decimal(38,2)))SELECT STR(testFloat, 38, 2)从Excel中导入到sql2000,有一列“联系方式”变成了float类型,我想转换成nvarchar类型,用下面的语句select convert(nvarchar(30),convert(int,联…

openjpa_OpenJPA:内存泄漏案例研究

openjpa本文将提供完整的根本原因分析详细信息以及解决影响Oracle Weblogic Server 10.0生产环境的Java堆内存泄漏(Apache OpenJPA泄漏)的方法。 这篇文章还将演示在管理javax.persistence.EntityManagerFactory生命周期时遵循Java Persistence API最佳实…

美国凯斯西储大学计算机硕士专业怎么样,在凯斯西储大学读硕士大约需要多少花费?...

凯斯西储大学是美国著名大学之一,始建于1826年,坐落于俄亥俄州的克里夫兰,是一所以独立研究闻名的世界顶级私立大学,美国一级国家级大学。美国作为当今世界留学费用最高的国家之一,费用问题是所有赴美留学的学生都非常…