zoukankan      html  css  js  c++  java
  • Spring Security:(一)入门案例

    Spring Security 简介

    Spring Security is a framework that provides authentication, authorization, and protection against common attacks. With first class support for both imperative and reactive applications, it is the de-facto standard for securing Spring-based applications.

    Spring Security 是一个提供身份验证、授权和针对常见攻击的保护的框架。 凭借对命令式和反应式应用程序的一流支持,它是保护基于 Spring 的应用程序的事实上的标准。

    项目搭建

    本项目基于 Spring Boot 框架,引入 Spring Security 依赖。数据库采用 mysql。

    引入依赖

    在项目的 pom.xml 文件中添加 Spring Security 的依赖坐标。

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

     这里 Spring Boot 用的版本是 2.1.12。 在 eclipse 或 idea 中可以查看到 spring-boot-starter-security 依赖的 Spring Security 版本是 5.1.7。下图是 spring-boot-starter-security 依赖的坐标文件:

    Spring Security 项目中有很多模块,包括如下模块:

    • spring-security-core
    • spring-security-remoting
    • spring-security-web
    • spring-security-config
    • spring-security-ldap
    • spring-security-oauth2-core
    • spring-security-oauth2-client
    • spring-security-oauth2-jose
    • spring-security-oauth2-resource-server
    • spring-security-acl
    • spring-security-cas
    • spring-security-openid
    • spring-security-test

    共 13 个模块。spring-boot-starter-security 只引用了其中的两个模块。

    测试接口

    在项目里添加一个接口,其代码如下:

    @RestController
    @RequestMapping("/app/api")
    public class AppController {
    
        @GetMapping("/hello")
        public String hello() {
            return "hello, app";
        }
    }

    此接口返回一个字符串,在未引入 Spring Security 可以请求获取数据。但引入 Spring Security 后重新启动项目,再次访问时就会提示要求输入账号密码了。

    访问 http://localhost:8080/app/api/hello 时,页面会跳转到 http://localhost:8080/login 页面,这是 Spring Security 源码中自带的一个简易登陆页面。项目在启动时 Spring Security 会自动创建一个名为 user 的用户,其密码会打印在控制台。

    在登陆页面输入 user 和对应的密码就可登陆成功,然后跳回到 http://localhost:8080/app/api/hello

    这样项目的接口就被 Spring Security 保护起来了,需要登录后才能访问。实际项目比上述 demo 要复杂,账号密码是从数据库中查询的,又或者项目是分布式的,这些内容后面文章逐点讲解。

  • 相关阅读:
    HTML<lable for="">标签的for属性。
    Microsoft_Office_Word_遇到问题需要关闭。我们对此引起的不便表示抱歉,问题解决方案
    AnyChart的资料,以后看
    JQquery 鼠标悬浮提示
    如何在SQL Server查询语句(Select)中检索存储过程(Store Procedure)的结果集?
    JQuery UI selectable
    SqlServer 动态添加服务器
    基于CyberGarage库的dlna开发(android)
    自定义实现圆形播放进度条(android,飞一般的感觉)
    Lance老师UI系列教程第一课>QQ设置界面的实现(android)
  • 原文地址:https://www.cnblogs.com/colin220/p/15595884.html
Copyright © 2011-2022 走看看