springSecurity实现简单的登录功能

前言

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 http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

2.效果

根目录可以直接通过验证,其他接口需要经过springSecurity,输入admin 123456后登陆系统

3.退出登陆

地址栏输入:http://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运算

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • SpringSecurity添加图形验证码认证实现

    目录 第一步:图形验证码接口 1.使用第三方的验证码生成工具Kaptcha 2.设置验证接口 3.模板表单设置 第二步:设置图像验证过滤器 第三步:将图像验证过滤器添加到springsecurity过滤器链中 第一步:图形验证码接口 1.使用第三方的验证码生成工具Kaptcha https://github.com/penggle/kaptcha @Configuration public class KaptchaImageCodeConfig { @Bean public DefaultKa

  • SpringSecurity注销设置的方法

    Spring Security中也提供了默认的注销配置,在开发时也可以按照自己需求对注销进行个性化定制 开启注销 默认开启 package com.example.config; import com.example.handler.MyAuthenticationFailureHandler; import com.example.handler.MyAuthenticationSuccessHandler; import org.springframework.context.annotat

  • SpringSecurity微服务实战之公共模块详解

    目录 前言 模块结构 前言 在项目中安全框架是必不可少的,在微服务架构中更是尤为重要,我们项目中将安全模块单独抽离了一个公共模块出来,因为在我的项目架构中 需要用到的SpringSecurity 至少有三个地方 boss服务 admin服务 user服务(saas)模式的一个微服务架构 模块结构 主要分为 base服务(提供数据,可以部署多份进行负载均衡) boss模块 admin模块 gateway模块 以及公共模块其中就包含我们今天的主角 安全模块. 我们在TokenLoginFilter中

  • SpringSecurity自定义登录成功处理

    有时候页面跳转并不能满足我们,特别是在前后端分离开发中就不需要成功之后跳转页面.只需要给前端返回一个JSON通知登录成功还是失败与否.这个试试可以通过自定义AuthenticationSuccessHandler实现 修改WebSecurityConfigurer successHandler package com.example.config; import com.example.handler.MyAuthenticationSuccessHandler; import org.spri

  • Spring Security 自定义授权服务器实践记录

    目录 前言 授权服务器变迁 最小化配置 安装授权服务器 配置授权服务器 配置客户端 体验 总结 前言 在之前我们已经对接过了GitHub.Gitee客户端,使用OAuth2 Client能够快速便捷的集成第三方登录,集成第三方登录一方面降低了企业的获客成本,同时为用户提供更为便捷的登录体验.但是随着企业的发展壮大,越来越有必要搭建自己的OAuth2服务器.OAuth2不仅包括前面的OAuth客户端,还包括了授权服务器,在这里我们要通过最小化配置搭建自己的授权服务器.授权服务器主要提供OAuth

  • SpringSecurity自定义登录界面

    为什么需要自定义登录界面? 答:因为SpringBoot整合SpringSecurity时,只需要一个依赖,无需其他配置,就可以实现认证功能.但是它的认证登录界面是固定那样的,如下图所示,但是我们希望自己搞个好看的登录界面,所以需要自定义登录界面. 第一步:创建springboot项目 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.or

  • SpringBoot浅析安全管理之Spring Security配置

    目录 Spring Security 的基本配置 基本用法 1. 创建项目添加依赖 2. 添加 hello 接口 3. 启动项目测试 配置用户名和密码 基于内存的认证 HttpSecurity 登录表单详细配置 注销登录配置 多个 HttpSecurity 密码加密 1. 为什么要加密 2. 加密方案 3. 实践 方法安全 在 Java 开发领域常见的安全框架有 Shiro 和 Spring Security.Shiro 是一个轻量级的安全管理框架,提供了认证.授权.会话管理.密码管理.缓存管理

  • Spring Security十分钟入门教程

    目录 写在前面 目标 开始 不引入Spring Security访问接口 引入Spring Security访问接口 退出登录 后记 写在前面 我们在学习技术的过程中,学习的渠道大概有以下几种:看书,视频,博客.我们会发现,一种技术开始流行的时候,各种形式的讲述也就出现了.那么,出书,录视频,写博客的人,在他们之前,是没有什么现成的东西让他们学习的,他们是怎么上手的呢?换句话说,怎么才能有效的快速的上手一门技术呢? 这篇文章,我们一起从零开始学习SpringSecurity,技术点不重要,重要的

  • Spring Security 自定义资源服务器实践过程

    目录 前言 最小化配置 安装资源服务器 配置资源服务器 配置客户端 整流程体验 总结 前言 在前面我们使用最小化配置的方式搭建了自己的授权服务器,现在我们依旧用最小化的方式配置自己的资源服务器.资源服务器负责scope的鉴权.authorities的鉴权.基于用户角色的鉴权等. 最小化配置 安装资源服务器 1. 新建一个Spring Boot项目,命名为spring-security-resource-server2.引入pom.xml依赖 <dependency> <groupId&g

  • springSecurity实现简单的登录功能

    前言 1.不使用数据库,实现一个简单的登录功能,只有在登录后才能访问我们的接口2.springSecurity提供了一种基于内存的验证方法(使用自己定义的用户,不使用默认的) 一.实现用户创建,登陆后才能访问接口(注重用户认证) 1.定义一个内存用户,不使用默认用户 重写configure(AuthenticationManagerBuilder auth)方法,实现在内存中定义一个 (用户名/密码/权限:admin/123456/admin) 的用户 package com.example.s

  • React Native实现简单的登录功能(推荐)

    React Native 简介: React Native 结合了 Web 应用和 Native 应用的优势,可以使用 JavaScript 来开发 iOS 和 Android 原生应用.在 JavaScript 中用 React 抽象操作系统原生的 UI 组件,代替 DOM 元素来渲染等. React Native 使你能够使用基于 JavaScript 和 React 一致的开发体验在本地平台上构建世界一流的应用程序体验.React Native 把重点放在所有开发人员关心的平台的开发效率上

  • php 实现简单的登录功能示例【基于thinkPHP框架】

    本文实例讲述了php 实现简单的登录功能.分享给大家供大家参考,具体如下: //登录页面: V层前端模板: Administrator@QCEE61NZ66FEX2D /cygdrive/c/wamp/www/thinkphp/Home/Tpl/Login $ ls index.html <!doctype html> <html lang="en"> <head> <meta name="Generator" conten

  • IDEA实现 springmvc的简单注册登录功能的示例代码

    1.基本环境搭建 spring简介 SpringMVC框架是以请求为驱动,围绕Servlet设计,将请求发给控制器,然后通过模型对象,分派器来展示请求结果视图.其中核心类是DispatcherServlet,它是一个Servlet,顶层是实现的Servlet接口. project创建 在图中填上项目名称即可,其他直接next 如上图所示,创建两个包,并且指定包的类型,如下图,java包指定为Sources Root,resouces包指定为Resources root 整个目录结构: pom依赖

  • 如何利用IDEA搭建SpringBoot项目整合mybatis实现简单的登录功能

    利用闲余时间想自己搭建一个springboot+mybatis的项目,提升一下自己对项目的了解,毕竟自己还是一个小白,在这里为自己创建项目的过程做一个记录,以便以后回忆.同时将搭建中遇到的问题也在这里做记录.如有遇到同样问题的同学,希望能给你一下借鉴. springboot的优势之一就是快速搭建项目,省去了自己导入jar包和配置xml的时间,使用非常方便. 一,搭建项目: 1.打开IDEA,点击File→New→Project...,如图1所示 图1  搭建项目 2.当我们选择project..

  • Servlet简单实现登录功能

    本文实例为大家分享了Servlet简单实现登录功能的具体代码,供大家参考,具体内容如下 介绍: Servlet 是 JavaWeb 三大组件之一.三大组件分别是:Servlet 程序.Filter 过滤器.Listener 监听器.Servlet 是运行在服务器上的一个 java 小程序,它可以接收客户端发送过来的请求,并响应数据给客户端. 学习内容: 1.编写Servlet程序 2.web.xml 中去配置 servlet 3.简单实现登录功能 具体步骤: 1.创建web工程,目录如下 2.创

  • SpringBoot + SpringSecurity 短信验证码登录功能实现

    实现原理 在之前的文章中,我们介绍了普通的帐号密码登录的方式: SpringBoot + Spring Security 基本使用及个性化登录配置. 但是现在还有一种常见的方式,就是直接通过手机短信验证码登录,这里就需要自己来做一些额外的工作了. 对SpringSecurity认证流程详解有一定了解的都知道,在帐号密码认证的过程中,涉及到了以下几个类:UsernamePasswordAuthenticationFilter(用于请求参数获取),UsernamePasswordAuthentica

  • Python的Flask框架中实现简单的登录功能的教程

     回顾 在前面的系列章节中,我们创建了一个数据库并且学着用用户和邮件来填充,但是到现在我们还没能够植入到我们的程序中. 两章之前,我们已经看到怎么去创建网络表单并且留下了一个实现完全的登陆表单. 在这篇文章中,我们将基于我门所学的网络表单和数据库来构建并实现我们自己的用户登录系统.教程的最后我们小程序会实现新用户注册,登陆和退出的功能. 为了能跟上这章节,你需要前一章节最后部分,我们留下的微博程序.请确保你的程序已经正确安装和运行. 在前面的章节,我们开始配置我们将要用到的Flask扩展.为了登

  • struts1实现简单的登录功能实例(附源码)

    环境:MyEclipse 14 1   struts1 框架搭建 在MyEclipse新建web project 取名为struts1_login,此时是一个空文档就不截图了然后在project上右键->选择myeclipse->add struts capabilities 单击上面Install Apache Struts(1.x)Facet 点击next 选择*.do ,改下包名改成与你项目相关的.如我的包名为com.lichang.struts1 点击next 点击完成,在我们的WEB

  • ajax 登录功能简单实现(未连接数据库)

    简单的登录功能(未连接数据库) 复制代码 代码如下: <script src="Jquery1.7.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $('#tijiao').click(function () { var username = $('#username').val(); va

随机推荐