14-项目集成SpringSecurity-定义Security配置类

新建com/itheima/stock/security/config/SecurityConfig.java

package com.itheima.stock.security.config;

import com.itheima.stock.security.filter.JwtLoginAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 密码匹配器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * 定义公共的无需被拦截的资源
     * @return
     */
    private String[] getPubPath(){
        //公共访问资源
        String[] urls = {
                "/**/*.css","/**/*.js","/favicon.ico","/doc.html",
                "/druid/**","/webjars/**","/v2/api-docs","/api/captcha",
                "/swagger/**","/swagger-resources/**","/swagger-ui.html"
        };
        return urls;
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //登出功能
        http.logout().logoutUrl("/api/logout").invalidateHttpSession(true);
        //开启允许iframe 嵌套。security默认禁用ifram跨域与缓存
        http.headers().frameOptions().disable().cacheControl().disable();
        //session禁用
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.csrf().disable();//禁用跨站请求伪造
        http.authorizeRequests()//对资源进行认证处理
                .antMatchers(getPubPath()).permitAll()//公共资源都允许访问
                .anyRequest().authenticated();  //除了上述资源外,其它资源,只有认证通过后,才能有权访问
        http.addFilterBefore(jwtLoginAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
    @Bean
    public JwtLoginAuthenticationFilter jwtLoginAuthenticationFilter() throws Exception {
        JwtLoginAuthenticationFilter filter = new JwtLoginAuthenticationFilter("/api/login");
        filter.setAuthenticationManager(authenticationManager());
        filter.setRedisTemplate(redisTemplate);
        return filter;
    }
}

启动stock_backend项目

先访问http://localhost:8091/api/captcha获取验证码和sessionId

再用postman测试一下,访问http://localhost:8091/api/login

 

 

返回的body

{
    "code": 1,
    "data": {
        "id": 1237361915165020161,
        "phone": "13888888888",
        "username": "admin",
        "nickName": "超级管理员",
        "realName": "小池",
        "sex": 1,
        "status": 1,
        "email": "[email protected]",
        "menus": [
            {
                "id": 1236916745927790564,
                "title": "组织管理",
                "icon": "el-icon-menu",
                "path": "/org",
                "name": "org",
                "children": [
                    {
                        "id": 1236916745927790560,
                        "title": "菜单权限管理",
                        "icon": "el-icon-menu",
                        "path": "/menus",
                        "name": "menus",
                        "children": []
                    },
                    {
                        "id": 1236916745927790575,
                        "title": "用户管理",
                        "icon": "el-icon-user-solid",
                        "path": "/user",
                        "name": "user",
                        "children": []
                    },
                    {
                        "id": 1236916745927790578,
                        "title": "角色管理",
                        "icon": "el-icon-user",
                        "path": "/roles",
                        "name": "roles",
                        "children": []
                    }
                ]
            },
            {
                "id": 1236916745927790569,
                "title": "系统管理",
                "icon": "el-icon-s-tools",
                "path": "/sys",
                "name": "sys",
                "children": [
                    {
                        "id": 1236916745927790558,
                        "title": "接口管理",
                        "icon": "el-icon-s-ticket",
                        "path": "/swagger",
                        "name": "swagger",
                        "children": []
                    },
                    {
                        "id": 1236916745927790571,
                        "title": "SQL监控",
                        "icon": "el-icon-s-data",
                        "path": "/sql",
                        "name": "sql",
                        "children": []
                    },
                    {
                        "id": 1236916745927790589,
                        "title": "日志管理",
                        "icon": "el-icon-user-solid",
                        "path": "/logs",
                        "name": "logs",
                        "children": []
                    }
                ]
            },
            {
                "id": 1469201551976435712,
                "title": "任务管理",
                "icon": "el-icon-menu",
                "path": "/jobAdmin",
                "name": "jobAdmin",
                "children": []
            }
        ],
        "permissions": [
            "btn-permission-delete",
            "btn-permission-list",
            "btn-permission-update",
            "btn-permission-add",
            "btn-user-delete",
            "btn-user-add",
            "btn-user-list",
            "btn-user-update-role",
            "btn-user-update",
            "btn-role-update",
            "btn-role-delete",
            "btn-role-add",
            "btn-role-detail",
            "btn-role-list",
            "btn-log-delete",
            "btn-log-list"
        ],
        "accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiW3N5czpwZXJtaXNzaW9uOmRlbGV0ZSwgc3lzOnBlcm1pc3Npb246bGlzdCwgc3lzOnBlcm1pc3Npb246dXBkYXRlLCBzeXM6cGVybWlzc2lvbjphZGQsIHN5czp1c2VyOmRlbGV0ZSwgc3lzOnVzZXI6YWRkLCBzeXM6dXNlcjpsaXN0LCBzeXM6dXNlcjpyb2xlOnVwZGF0ZSwgc3lzOnVzZXI6dXBkYXRlLCBzeXM6cm9sZTp1cGRhdGUsIHN5czpyb2xlOmRlbGV0ZSwgc3lzOnJvbGU6YWRkLCBzeXM6cm9sZTpkZXRhaWwsIHN5czpyb2xlOmxpc3QsIHN5czpsb2c6ZGVsZXRlLCBzeXM6bG9nOmxpc3QsIFJPTEVf6LaF57qn566h55CG5ZGYXSIsImV4cCI6MTcwNjI4MzcwMiwiaWF0IjoxNzA1Njc4OTAyLCJ1c2VybmFtZSI6ImFkbWluIn0.dMMAdjZgTRvdwPhkbhK5m4VFK2v51crLhWkUQDhNBDI"
    }
}