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": "875267425@qq.com",
        "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"
    }
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring MVC是一种基于MVC设计模式的轻量级Java框架,而Spring Security是一个专门用于身份验证和授权的安全框架。将Spring MVC项目集成Spring Security可以为项目提供更强大的安全性。 在Spring MVC项目集成Spring Security的步骤如下: 1. 添加Spring Security依赖:在项目的pom.xml文件中添加Spring Security的依赖项,以便在项目中使用Spring Security的功能。 2. 配置Spring Security:创建一个SecurityConfig,用于配置Spring Security的相关设置。可以在其中配置用户认证方式、权限管理和安全规则等。 3. 自定义用户认证:可以实现UserDetailsService接口,并重写loadUserByUsername方法来提供自定义的用户认证逻辑。也可以使用自定义的AuthenticationProvider来验证用户的身份。 4. 配置安全规则:可以通过配置AntMatchers来定义不同URL路径的访问权限。可以设置哪些角色或权限可以访问某个URL路径。 5. 配置登录和注销页面:创建登录和注销的控制器,并配置登录表单的提交地址和注销地址。可以为登录页面自定义视图,并对登录请求进行处理。 6. 使用安全注解:可以在控制器或方法上使用Spring Security提供的安全注解,如@PreAuthorize和@Secured,来对方法或URL进行细粒度的授权。 7. 使用Spring Security的标签库:可以使用相应的标签库来在JSP页面中展示用户信息、权限信息等。也可以通过标签来控制页面上的内容是否展示。 通过以上步骤,就可以在Spring MVC项目中成功集成Spring Security集成后,项目将具备强大的身份验证和授权功能,能够有效保护项目的安全性,并对不同用户或角色进行权限控制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码的翠花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值