如何通过springSecurity实现基础登录流程?
- 内容介绍
- 文章标签
- 相关推荐
本文共计2082个文字,预计阅读时间需要9分钟。
前言
1.不使用数据库,实现一个简单的登录功能。
2.登录后才能访问我们的接口。
3.使用Spring Security提供了一种基于内存的验证方法(使用自定义的用户,不使用默认的)。
一、实现登录功能
1.创建一个简单的登录页面,收集用户名和密码。
2.使用Spring Security进行身份验证。
3.验证成功后,重定向到首页。
二、使用Spring Security提供的基于内存的验证方法
1.配置Spring Security的配置文件,定义用户名和密码。
2.在Spring Security的配置文件中,配置自定义的UserDetailsService实现。
3.实现UserDetailsService接口,加载用户信息到内存中。
三、访问接口
1.登录成功后,用户可以访问我们的接口。
2.如果未登录,接口将返回401错误。
前言
1、不使用数据库,实现一个简单的登录功能,只有在登录后才能访问我们的接口
2、springSecurity提供了一种基于内存的验证方法(使用自己定义的用户,不使用默认的)
一、实现用户创建,登陆后才能访问接口(注重用户认证)
1.定义一个内存用户,不使用默认用户
重写configure(AuthenticationManagerBuilder auth)方法,实现在内存中定义一个 (用户名/密码/权限:admin/123456/admin) 的用户
package com.example.springsecurity; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity localhost:8080/login?logout,执行退出登陆
4.再创建一个张三用户,同时支持多用户登陆
package com.example.springsecurity; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理 http.authorizeRequests() //安全过滤策略 .antMatchers("/").permitAll() .anyRequest().authenticated() .and() //and添加允许别的操作 .logout().permitAll() //允许支持注销,支持随意访问 .and() .formLogin(); //允许表单登录 http.csrf().disable(); //关闭csrf认证 } }
二、实现管理员功能(注重权限控制)
实现角色功能,不同角色拥有不同功能:管理员拥有管理功能,而普通组员只能拥有最普通的功能
1.创建一个普通用户demo
auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");
创建demo用户,角色为demo,详细代码如下
package com.example.springsecurity; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user"); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理 http.authorizeRequests() //安全过滤策略 .antMatchers("/").permitAll() .anyRequest().authenticated() .and() //and添加允许别的操作 .logout().permitAll() //允许支持注销,支持随意访问 .and() .formLogin(); //允许表单登录 http.csrf().disable(); //关闭csrf认证 } }
2.创建/roleAuth接口
此接口只能admin角色才能登陆
1)、@EnableGlobalMethodSecurity注解使role验证注解生效
2)、@PreAuthorize(“hasRole(‘ROLE_admin’)”)注解声明哪个角色能访问此接口
package com.example.springsecurity; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication @EnableGlobalMethodSecurity(prePostEnabled = true) //必须加这行,不然role验证无效 public class SpringsecurityApplication { public static void main(String[] args) { SpringApplication.run(SpringsecurityApplication.class, args); } @RequestMapping("/") public String home(){ return "hello spring boot"; } @RequestMapping("/hello") public String hello(){ return "hello word"; } @PreAuthorize("hasRole('ROLE_admin')") //当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写 @RequestMapping("/roleAuth") public String role(){ return "admin Auth"; } }
3.效果
demo用户登陆成功可以访问/接口,但是不能访问/roleAuth接口
admin管理员既能访问/接口,也能访问/roleAuth接口
三、实现数据库管理用户(注重数据库认证用户)
1.我们需要把之前创建的admin zhangsan demo三个用户放到数据库中 2.我们需要使用MyUserService来管理这些用户
1.创建一个MyUserService类
1.此类实现UserDetailsService(这边不真实查询数据库)
package com.example.springsecurity; 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 MyUserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { return null;//数据库操作逻辑 } }
2.密码自定义验证类
1.此类实现自定义密码验证
package com.example.springsecurity; import org.springframework.security.authentication.encoding.Md5PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; public class MyPasswdEncoder implements PasswordEncoder { private final static String SALT = "123456"; @Override public String encode(CharSequence rawPassword) { //加密:堆原始的密码进行加密,这边使用md5进行加密 Md5PasswordEncoder encoder = new Md5PasswordEncoder(); return encoder.encodePassword(rawPassword.toString(), SALT); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { //拿原始的密码和加密后的密码进行匹配 Md5PasswordEncoder encoder = new Md5PasswordEncoder(); return encoder.isPasswordValid(encodedPassword,rawPassword.toString(),SALT); } }
3.自定义数据库查询&默认数据库查询、自定义密码验证配置
1.支持自定义数据库查询 2.支持默认数据库查询(数据库结构必须和默认的一致) 两者选择其中一个
package com.example.springsecurity; import org.springframework.beans.factory.annotation.Autowired; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired MyUserService myUserService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 // auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); // auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); // auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user"); //1、自己实现数据库的查询,指定我们要使用的UserService和自定义的密码验证器 auth.userDetailsService(myUserService).passwordEncoder(new MyPasswdEncoder()); //2、sprinSecurity在数据库管理方面支持一套默认的处理,可以指定根据用户查询,权限查询,这情况下用户表必须和默认的表结构相同,具体查看user.ddl文件 auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswdEncoder()); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理 http.authorizeRequests() //安全过滤策略 .antMatchers("/").permitAll() .anyRequest().authenticated() .and() //and添加允许别的操作 .logout().permitAll() //允许支持注销,支持随意访问 .and() .formLogin(); //允许表单登录 http.csrf().disable(); //关闭csrf认证 } }
四、sprinSecurity支持的4种使用表达式的权限注解
1.支持的4种注解
@PreAuthorize("hasRole('ROLE_admin')") //1.方法调用前:当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写 @PostAuthorize("hasRole('ROLE_admin')")//2.方法调用后 @PreFilter("")//2.对集合类的参数或返回值进行过滤 @PostFilter("")//2.对集合类的参数或返回值进行过滤 @RequestMapping("/roleAuth") public String role(){ return "admin Auth"; }
2.注解的参数该怎么传
or用法:
参数的值判断
and运算
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。
本文共计2082个文字,预计阅读时间需要9分钟。
前言
1.不使用数据库,实现一个简单的登录功能。
2.登录后才能访问我们的接口。
3.使用Spring Security提供了一种基于内存的验证方法(使用自定义的用户,不使用默认的)。
一、实现登录功能
1.创建一个简单的登录页面,收集用户名和密码。
2.使用Spring Security进行身份验证。
3.验证成功后,重定向到首页。
二、使用Spring Security提供的基于内存的验证方法
1.配置Spring Security的配置文件,定义用户名和密码。
2.在Spring Security的配置文件中,配置自定义的UserDetailsService实现。
3.实现UserDetailsService接口,加载用户信息到内存中。
三、访问接口
1.登录成功后,用户可以访问我们的接口。
2.如果未登录,接口将返回401错误。
前言
1、不使用数据库,实现一个简单的登录功能,只有在登录后才能访问我们的接口
2、springSecurity提供了一种基于内存的验证方法(使用自己定义的用户,不使用默认的)
一、实现用户创建,登陆后才能访问接口(注重用户认证)
1.定义一个内存用户,不使用默认用户
重写configure(AuthenticationManagerBuilder auth)方法,实现在内存中定义一个 (用户名/密码/权限:admin/123456/admin) 的用户
package com.example.springsecurity; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity localhost:8080/login?logout,执行退出登陆
4.再创建一个张三用户,同时支持多用户登陆
package com.example.springsecurity; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理 http.authorizeRequests() //安全过滤策略 .antMatchers("/").permitAll() .anyRequest().authenticated() .and() //and添加允许别的操作 .logout().permitAll() //允许支持注销,支持随意访问 .and() .formLogin(); //允许表单登录 http.csrf().disable(); //关闭csrf认证 } }
二、实现管理员功能(注重权限控制)
实现角色功能,不同角色拥有不同功能:管理员拥有管理功能,而普通组员只能拥有最普通的功能
1.创建一个普通用户demo
auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");
创建demo用户,角色为demo,详细代码如下
package com.example.springsecurity; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user"); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理 http.authorizeRequests() //安全过滤策略 .antMatchers("/").permitAll() .anyRequest().authenticated() .and() //and添加允许别的操作 .logout().permitAll() //允许支持注销,支持随意访问 .and() .formLogin(); //允许表单登录 http.csrf().disable(); //关闭csrf认证 } }
2.创建/roleAuth接口
此接口只能admin角色才能登陆
1)、@EnableGlobalMethodSecurity注解使role验证注解生效
2)、@PreAuthorize(“hasRole(‘ROLE_admin’)”)注解声明哪个角色能访问此接口
package com.example.springsecurity; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication @EnableGlobalMethodSecurity(prePostEnabled = true) //必须加这行,不然role验证无效 public class SpringsecurityApplication { public static void main(String[] args) { SpringApplication.run(SpringsecurityApplication.class, args); } @RequestMapping("/") public String home(){ return "hello spring boot"; } @RequestMapping("/hello") public String hello(){ return "hello word"; } @PreAuthorize("hasRole('ROLE_admin')") //当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写 @RequestMapping("/roleAuth") public String role(){ return "admin Auth"; } }
3.效果
demo用户登陆成功可以访问/接口,但是不能访问/roleAuth接口
admin管理员既能访问/接口,也能访问/roleAuth接口
三、实现数据库管理用户(注重数据库认证用户)
1.我们需要把之前创建的admin zhangsan demo三个用户放到数据库中 2.我们需要使用MyUserService来管理这些用户
1.创建一个MyUserService类
1.此类实现UserDetailsService(这边不真实查询数据库)
package com.example.springsecurity; 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 MyUserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { return null;//数据库操作逻辑 } }
2.密码自定义验证类
1.此类实现自定义密码验证
package com.example.springsecurity; import org.springframework.security.authentication.encoding.Md5PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; public class MyPasswdEncoder implements PasswordEncoder { private final static String SALT = "123456"; @Override public String encode(CharSequence rawPassword) { //加密:堆原始的密码进行加密,这边使用md5进行加密 Md5PasswordEncoder encoder = new Md5PasswordEncoder(); return encoder.encodePassword(rawPassword.toString(), SALT); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { //拿原始的密码和加密后的密码进行匹配 Md5PasswordEncoder encoder = new Md5PasswordEncoder(); return encoder.isPasswordValid(encodedPassword,rawPassword.toString(),SALT); } }
3.自定义数据库查询&默认数据库查询、自定义密码验证配置
1.支持自定义数据库查询 2.支持默认数据库查询(数据库结构必须和默认的一致) 两者选择其中一个
package com.example.springsecurity; import org.springframework.beans.factory.annotation.Autowired; 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.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired MyUserService myUserService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基于内存的验证方法 // auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); // auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); // auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user"); //1、自己实现数据库的查询,指定我们要使用的UserService和自定义的密码验证器 auth.userDetailsService(myUserService).passwordEncoder(new MyPasswdEncoder()); //2、sprinSecurity在数据库管理方面支持一套默认的处理,可以指定根据用户查询,权限查询,这情况下用户表必须和默认的表结构相同,具体查看user.ddl文件 auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswdEncoder()); } @Override public void configure(WebSecurity web) throws Exception { //批处理静态资源,都不拦截处理 web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理 http.authorizeRequests() //安全过滤策略 .antMatchers("/").permitAll() .anyRequest().authenticated() .and() //and添加允许别的操作 .logout().permitAll() //允许支持注销,支持随意访问 .and() .formLogin(); //允许表单登录 http.csrf().disable(); //关闭csrf认证 } }
四、sprinSecurity支持的4种使用表达式的权限注解
1.支持的4种注解
@PreAuthorize("hasRole('ROLE_admin')") //1.方法调用前:当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写 @PostAuthorize("hasRole('ROLE_admin')")//2.方法调用后 @PreFilter("")//2.对集合类的参数或返回值进行过滤 @PostFilter("")//2.对集合类的参数或返回值进行过滤 @RequestMapping("/roleAuth") public String role(){ return "admin Auth"; }
2.注解的参数该怎么传
or用法:
参数的值判断
and运算
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

