Spring Cloud 整合 security主要配置

推荐博客园地址

https://www.cnblogs.com/toov5/p/10324913.html

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

import com.mayikt.handler.MyAuthenticationFailureHandler;
import com.mayikt.handler.MyAuthenticationSuccessHandler;

// Security 配置
@Component
@EnableWebSecurity                  //继承这个类
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private MyAuthenticationFailureHandler failureHandler;
  @Autowired
  private MyAuthenticationSuccessHandler successHandler;
    // 配置认证用户信息和权限
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 添加admin账号
        auth.inMemoryAuthentication().withUser("admin").password("123456").
        authorities("showOrder","addOrder","updateOrder","deleteOrder");
        // 添加userAdd账号
        auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
        // 如果想实现动态账号与数据库关联 在该地方改为查询数据库
 
    }

    // 配置拦截请求资源
    protected void configure(HttpSecurity http) throws Exception {
        // 如何权限控制 给每一个请求路径 分配一个权限名称 让后账号只要关联该名称,就可以有访问权限
        http.authorizeRequests()
        // 配置查询订单权限
        .antMatchers("/showOrder").hasAnyAuthority("showOrder")
        .antMatchers("/addOrder").hasAnyAuthority("addOrder")
        .antMatchers("/login").permitAll() //登录请求不可以拦截!
        .antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
        .antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
        .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").  //配置登录页面!!
        successHandler(successHandler).failureHandler(failureHandler)   //成功和失败的配置
        .and().csrf().disable();   //csrf跨站点攻击关闭 否则必须要传递token!!      
    }

	//因为是测试项目所以就不需要加密解密
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

}

配置认证

//认证失败
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
            throws IOException, ServletException {
        System.out.println("登陆失败!");
        res.sendRedirect("http://baidu.com");

    }

}
// 认证成功
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication arg2)
            throws IOException, ServletException {
        System.out.println("用户认证成功");
        res.sendRedirect("/");
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring CloudSpring Security是两个独立的框架,Spring Cloud用于构建分布式系统和微服务架构,而Spring Security用于实现安全性和身份验证。 在Spring Cloud中,可以使用Spring Security来实现服务之间的安全通信,以及对微服务进行身份验证和授权等操作。下面是Spring Cloud整合Spring Security的步骤: 1. 添加Spring Security依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> ``` 2. 配置Spring SecuritySpring Cloud微服务的配置文件中,添加以下配置: ``` security: basic: enabled: true user: name: user password: password ``` 这里配置了基本的HTTP身份验证,并指定了用户名和密码。 3. 创建Spring Security配置类 创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure(HttpSecurity http)方法,配置安全策略和访问权限等。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } } ``` 这里配置了所有请求都需要进行身份验证,并使用基本的HTTP身份验证。 4. 配置微服务访问授权 在Spring Cloud微服务的配置文件中,添加以下配置: ``` security: oauth2: resource: jwt: key-value: "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwJLdYVgFzX9QY+7Adk6x\n...(JWT密钥)\n-----END PUBLIC KEY-----" ``` 这里配置了OAuth2资源服务器使用JWT令牌进行访问授权,并指定了JWT密钥。 5. 创建OAuth2资源服务器配置类 创建一个继承自ResourceServerConfigurerAdapter的配置类,并重写configure(HttpSecurity http)方法,配置资源服务器的安全策略和访问权限等。 ``` @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().permitAll(); } } ``` 这里配置了所有/api/**的请求需要进行身份验证,其他请求允许匿名访问。 6. 测试安全性 启动Spring Cloud微服务,并使用curl或Postman等工具进行测试。 例如,使用curl命令进行基本身份验证: ``` curl -u user:password http://localhost:8080 ``` 使用curl命令进行JWT令牌访问授权: ``` curl --header "Authorization: Bearer <JWT令牌>" http://localhost:8080/api ``` 以上就是Spring Cloud整合Spring Security的基本步骤,可以根据具体的需求进行灵活配置和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值