springcloud之Feign初识篇—注解实现服务认证

我们知道feign是HTTP请求的所以有的时候需要添加些头部参数什么的,这些参数通常是通过feign的配置信息来添加的。

例:我们的服务提供者设置了安全校验,需要配置账号、密码才能正式请求。

服务提供者:

1、pom添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2、配置yml

spring:
  application:
    name: test1
  security:
    user:
      name: root
      password: root

3、java设置所有访问都需要安全认证

import org.springframework.context.annotation.Configuration;
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;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //禁用csrf
        http.csrf().disable();
        // 表示所有的访问都必须认证,认证处理后才可以正常进行
        http.httpBasic().and().authorizeRequests().anyRequest().fullyAuthenticated();
        // 所有的rest服务一定要设置为无状态,以提升操作效率和性能
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

此时服务消费者调用服务提供者报错:出现401是因为服务提供者设置了请求需要进行认证处理

服务消费者配置认证:

//@Configuration:启用该注解后该类会被所有@feign加载,所以最好不在这里使用
public class FeignAuthConfiguration {

    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){
        return new BasicAuthRequestInterceptor("root","root");
    }
}

调用服务的接口注解上添加该配置类:

//我们每个接口类会调用不同服务的信息,所以configuration对应的类可能会不同
@FeignClient(name = "test1",configuration = FeignAuthConfiguration.class)
public interface FeignTest1Service {

    @RequestMapping(value = "/ribbonTest",method = RequestMethod.POST)
    public String testFeign(@RequestBody Map<String,String> map);
}

 @Configuration:启用该注解后该类会被所有@feign加载,所有@feign都会使用该配置类信息

启动服务消费者再次调用:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值