当前位置: 首页 > news >正文

Spring boot 集成Spring Security

 

依赖jar

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

 

 

示例如下:

1.   新建Maven项目 security

 

2.   pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/xsd/maven-4.0.0.xsd">


    <modelVersion>4.0.0</modelVersion>
    <groupId>com.java</groupId>
    <artifactId>security</artifactId>
    <version>1.0.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>


    <dependencies>

        <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>


        <!-- 热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
            <version>1.2.8.RELEASE</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

 

3.   SecurityStarter.java

package com.java;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * <blockquote><pre>
 * 
 * 主启动类
 * 
 * </pre></blockquote>
 * 
 *
 */
@SpringBootApplication
public class SecurityStarter {

    public static void main(String[] args) {
        SpringApplication.run(SecurityStarter.class, args);
    }

}

 

4.   HostController.java

package com.java.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

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

@RestController
public class HostController {

    @GetMapping("/getHostMessage")
    public Map<String, Object> getHostMessage() {
        Map<String, Object> map = new HashMap<>();
        try {
            InetAddress serverHost = InetAddress.getLocalHost();
            map.put("hostname", serverHost.getHostName());
            map.put("hostAddress", serverHost.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
            map.put("msg", e.getMessage());
        }

        return map;

    }

}

 

5.   ApplicationContextConfig.java

package com.java.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 配置文件类
 *
 */
@Configuration
public class ApplicationContextConfig {

    /**
     * <blockquote><pre>
     * 
     * 配置密码编码器,Spring Security 5.X必须配置,否则登录时报空指针异常
     * 
     * </pre></blockquote>
     * 
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

 

6.   SecurityUserDetailsService.java

package com.java.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SecurityUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 数据库存储密码为加密后的密文(明文为123456)
        String password = passwordEncoder.encode("123456");

        System.out.println("username: " + username);
        System.out.println("password: " + password);

        // 模拟查询数据库,获取属于Admin和Normal角色的用户
        User user = new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("Admin,Normal"));

        return user;
    }

}

 

 

7.   运行 SecurityStarter.java ,启动项目

 浏览器输入   http://localhost:8080/getHostMessage

自动跳转到登录界面,截图如下:

输入如下信息:

User:Logen

Password:123456

 

 点击【Login】按钮,自动跳转回刚才访问页面http://localhost:8080/getHostMessage

 返回信息如下:

{"hostname":"Logen","hostAddress":"192.168.1.102"}

 

 输入其它密码,将提示<坏的凭证>

 

 

 搭建完成!

.

转载于:https://www.cnblogs.com/jonban/p/10321814.html

相关文章:

  • Java 异常表与异常处理原理
  • 中国最高法、全国工商联联合发文促商会调解发挥作用
  • 每个JavaScript开发人员应阅读的书【1】 - JavaScript: The Good Parts
  • 《程序是怎样跑起来的》第三章读后感
  • 加密与安全部分 实验及知识点
  • java springboot b2b2c shop 多用户商城系统源码-(七)高可用的分布式配置中心(Spring Cloud Config)...
  • 如何利用分层测试概念设计针对性测试用例
  • Firefox 66 将自带自动屏蔽声音功能
  • npm install 报错
  • as3调用外部应用程序 as调用外部exe文件as3调用bat文件 未测试
  • 使用Linux中的 v i m 编辑器
  • Chrome 72 禁止第三方程序代码注入
  • python博客
  • windows2012服务器中安装php7+mysql5.7+apache2.4环境
  • Python 基础起步 (十) 什么叫函数?
  • 〔开发系列〕一次关于小程序开发的深度总结
  • javascript面向对象之创建对象
  • maven工程打包jar以及java jar命令的classpath使用
  • MaxCompute访问TableStore(OTS) 数据
  • MYSQL 的 IF 函数
  • Sublime Text 2/3 绑定Eclipse快捷键
  • 阿里云ubuntu14.04 Nginx反向代理Nodejs
  • 回顾2016
  • 基于axios的vue插件,让http请求更简单
  • 记录一下第一次使用npm
  • 开源地图数据可视化库——mapnik
  • 深入浅出webpack学习(1)--核心概念
  • 数据仓库的几种建模方法
  • 扩展资源服务器解决oauth2 性能瓶颈
  • ​io --- 处理流的核心工具​
  • ​人工智能书单(数学基础篇)
  • # C++之functional库用法整理
  • #laravel 通过手动安装依赖PHPExcel#
  • (1)(1.13) SiK无线电高级配置(五)
  • (2)(2.4) TerraRanger Tower/Tower EVO(360度)
  • (33)STM32——485实验笔记
  • (4)事件处理——(6)给.ready()回调函数传递一个参数(Passing an argument to the .ready() callback)...
  • (bean配置类的注解开发)学习Spring的第十三天
  • (pytorch进阶之路)CLIP模型 实现图像多模态检索任务
  • (solr系列:一)使用tomcat部署solr服务
  • (非本人原创)史记·柴静列传(r4笔记第65天)
  • (分享)一个图片添加水印的小demo的页面,可自定义样式
  • (新)网络工程师考点串讲与真题详解
  • (一)Mocha源码阅读: 项目结构及命令行启动
  • (一)UDP基本编程步骤
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • (转)Linux下编译安装log4cxx
  • .gitignore文件—git忽略文件
  • .NET 4.0网络开发入门之旅-- 我在“网” 中央(下)
  • .Net Core/.Net6/.Net8 ,启动配置/Program.cs 配置
  • .NET gRPC 和RESTful简单对比
  • .net MySql
  • ?php echo ?,?php echo Hello world!;?
  • [ vulhub漏洞复现篇 ] struts2远程代码执行漏洞 S2-005 (CVE-2010-1870)
  • []FET-430SIM508 研究日志 11.3.31