简体   繁体   English

如何使用邮递员将用户登录详细信息传递给Spring Boot Rest API

[英]How to pass user login details to Spring Boot Rest API using postman

I am creating an API using Spring Boot Rest, I want to restrict the API so only logged in users can access it. 我正在使用Spring Boot Rest创建API,我想限制API,因此只有登录用户才能访问它。 Now to test the API I am using postman, but how to pass the user details to the API? 现在测试我使用邮递员的API,但是如何将用户详细信息传递给API?

Here is my code: 这是我的代码:

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers(HttpMethod.GET, "/", "/orders").permitAll()
        .antMatchers(HttpMethod.POST, "/order/**").hasAnyRole("ADMIN")
        .antMatchers(HttpMethod.DELETE, "/order/**").hasAnyRole("ADMIN")
        .and()
        .exceptionHandling().accessDeniedHandler(accessDeniedHandler);

    }

    // create two users, admin and user
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
                .and()
                .withUser("admin").password("password").roles("ADMIN");
    }
}

Here is my access denied handler: 这是我的访问被拒绝处理程序:

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    private static Logger logger = LoggerFactory.getLogger(MyAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {

        Authentication auth
                = SecurityContextHolder.getContext().getAuthentication();

        if (auth != null) {
            logger.info("User '" + auth.getName()
                    + "' attempted to access the protected URL: "
                    + httpServletRequest.getRequestURI());
        }
        httpServletResponse.setContentType("application/json");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.print("Wrong user");

    }
}

When I try to access the API with URL as order and method as DELETE using postman and passing user login details using Authorization tab with Basic Auth and passing Username as admin and password as password , I am getting Wrong user message. 当我尝试使用URL作为order和方法访问API作为DELETE使用postman并使用带有Basic Auth Authorization选项卡传递用户登录详细信息并将Username作为admin和密码作为password传递,我收到了Wrong user消息。

How to pass the user loin details to my API using postman ? 如何使用postman将用户腰部细节传递给我的API?

Maybe form login is the default auth mechanism and you need to specify that you want to use Basic Auth. 也许表单登录是默认的身份验证机制,您需要指定要使用基本身份验证。

Try this: 试试这个:

@Configuration
class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private AccessDeniedHandler accessDeniedHandler;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers(HttpMethod.GET, "/", "/orders").permitAll()
      .antMatchers(HttpMethod.POST, "/order/**").hasAnyRole("ADMIN")
      .antMatchers(HttpMethod.DELETE, "/order/**").hasAnyRole("ADMIN")
      .and()
      .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
    .and()  //added
    .httpBasic();  //added

  }

  // create two users, admin and user
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication()
      .withUser("user").password("password").roles("USER")
      .and()
      .withUser("admin").password("password").roles("ADMIN");
  }
}

What you need is the following dependency (You might have it already): 您需要的是以下依赖项(您可能已经拥有它):

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

Than you can create a user in your application.properties file: 您可以在application.properties文件中创建用户:

security.user.name=username
security.user.password=password

If you are using Spring 2.0.0 M4 or higher use "spring.security". 如果您使用的是Spring 2.0.0 M4或更高版本,请使用“spring.security”。

Now go to Postman under "Authorization" use "Basic Auth" and fill in the credenrtials you have set in the properties file. 现在在“授权”下使用“基本身份验证”转到邮递员,并填写您在属性文件中设置的证书。

Hope this is what you are looking for. 希望这是你正在寻找的。 Good luck:) 祝好运:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在rest控制器spring boot中为邮递员生成api-key - how to generate api-key for postman in rest controller spring boot 如何在spring boot rest&postman中使用表单数据来保存用户? - How to save user by using form-data in spring boot rest & postman? 如何使用 Postman 在 Spring Boot 的请求参数中传递时间戳、日期 - How to pass Timestamp,date in request param in spring boot using Postman Spring REST Api —访问存储库中的用户详细信息 - Spring REST Api — access User details in repository 如何使用Spring Boot,JPA,Hibernate和MySQL验证用户登录并传递JWT令牌 - How to authenticate user login and pass JWT token using spring boot, jpa,hibernate and mysql 如何将整数列表作为 json 数据传递给 spring 引导 rest ZDB974238714CA8DE634A7ACE14 - How to pass the list of integers as json data to spring boot rest API? Spring-boot rest api当前请求不是邮递员的多部分请求 - Spring-boot rest api current request is not multipart request with postman 如何在邮递员中将多个字符串包装成单个字符串以调用spring boot rest API Get请求 - How to wrap multiple strings into single string in postman to call spring boot rest API Get request 如何解决通过 Z03D476861AFD3854510 测试 spring 引导 rest api 时遇到的错误? - How can I solve the error I get while testing the spring boot rest api via postman? 无法通过 spring-boot-starter-test 测试 Spring Boot REST API,而相同的“api”正在为 Postman 工作 - Unable to test Spring Boot REST API by spring-boot-starter-test while same "api" is working for Postman
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM