zoukankan      html  css  js  c++  java
  • 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"}

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

     搭建完成!

    .

  • 相关阅读:
    剑指offer--50.滑动窗口的最大值
    剑指offer--49.矩阵中的路径
    剑指offer--48.机器人的运动范围
    剑指offer--47.数据流中的中位数
    剑指offer--46.字符流中第一个不重复的字符
    剑指offer--45.二叉树的深度
    剑指offer--44.两个链表的第一个公共结点
    剑指offer--43.连续子数组的最大和
    海盗分宝石问题
    C++数组名退化指针实例
  • 原文地址:https://www.cnblogs.com/jonban/p/10321814.html
Copyright © 2011-2022 走看看