Postman ошибка 401

I am developing rest APIs in Spring Boot. I am able to do CRUD operations and postman gives correct responses, but when I add Spring Security username and password Postman gives 401 Unauthorized.

I have provided a spring boot security username and password as below.

application.proptries

spring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/pal?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.security.user.name=root
spring.security.user.password=root

I have done basic auth with username as root and password as root.
Preview request gives headers updated successfully message :

enter image description here

EDIT
I have deleted the cookies in postman but still facing the same issue

SecurityConfing.java
My Security Configuration are as below. 
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
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;

@Configuration
@EnableWebSecurity
@Order(1000)
public class SecurityConfig extends WebSecurityConfigurerAdapter{


    public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {

        authenticationMgr.jdbcAuthentication().dataSource(dataSource())
          .usersByUsernameQuery(
           "select email,password from user where email=? and statusenable=true")
          .authoritiesByUsernameQuery(
           "select email,role from user where email=? and statusenable=true");

        System.out.println(authenticationMgr.jdbcAuthentication().dataSource(dataSource())
          .usersByUsernameQuery(
           "select email,password from user where email=? and statusenable=true")
          .authoritiesByUsernameQuery(
           "select email,role from user where email=? and statusenable=true"));
    }

    @Bean(name = "dataSource")
     public DriverManagerDataSource dataSource() {
         DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
         driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
         driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/pal");
         driverManagerDataSource.setUsername("root");
         driverManagerDataSource.setPassword("");
         return driverManagerDataSource;
     }

    @Override
     protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .authorizeRequests().antMatchers("/login").permitAll()
    .anyRequest().authenticated()
    .and()
    .formLogin().loginPage("/login").permitAll()
    .and()
    .authorizeRequests().antMatchers("/admin/**").hasAnyRole("ROLE_ADMIN","ROLE_USER").anyRequest().permitAll()
    .and()
    .authorizeRequests().antMatchers("/user/**").hasAnyRole("ROLE_USER").anyRequest().permitAll();

}

asked Feb 19, 2019 at 4:29

Romil Patel's user avatar

Romil PatelRomil Patel

12.6k7 gold badges44 silver badges74 bronze badges

2

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
       http.csrf().disable().authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers(HttpMethod.POST,"/newuser").permitAll()
        .antMatchers(HttpMethod.POST, "/login").permitAll()
        .antMatchers(HttpMethod.POST,"/newuser/*").permitAll()
        .antMatchers(HttpMethod.GET,"/master/*").permitAll()
         .antMatchers(HttpMethod.GET,"/exploreCourse").permitAll()
        .anyRequest().authenticated()
    }
}

You need to configure Spring Security, by default all routes all secured for authrorization.

Please have a look JWT Token implementation at this Link.

answered Feb 19, 2019 at 7:41

Nishant Varshney's user avatar

9

If Authorization needed in spring boot, the below annotation at root configuration class.

@EnableAuthorizationServer
( and other required annotations)
public class Application{
....
....
}

Below dependency also needed to be added

<dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        </dependency>

answered Jan 14, 2021 at 10:21

sub's user avatar

subsub

4971 gold badge7 silver badges20 bronze badges

We quite often see these 401 Unauthorized issues in Postman, even after connected to Dataverse environment and also all the required setups done in Postman.

This issue can be due to the existing Token expiration.

Follow the below steps to regenerate the Token in Postman.

Step 1: Navigate to your collection and Click on Get New Access Token.

Once, you get the New Access Token, you can see the below message.

Step 2: New Token will be generated automatically and Click on Use Token to use this for executing the Web API’s.

Step 3: Click on Access Token dropdown and Click on Manage Tokens.

You can see the all the Tokens information.

All Available Tokens are displayed without a strike text and Expired Tokens are displayed with a strike text.

Step 4: Hover on the Expired Token, Click on Delete icon to delete it.

Step 5: Expired Token is deleted and Close the MANAGE ACCESS TOKENS popup.

Step 6: Go back to your Web API request.

Click on Send to execute your Web API and see the results.

Hope you have successfully resolved this issue and able to connect to Dynamics 365.

Please share your valuable feedback on this article.

Articles you might like related to Dynamics 365 CE.

How to Download and Install Postman on your PC?

How to Register an App in Azure Active Directory for Dynamics 365 CE Online?

How to setup and connect to the Dataverse environment in Postman?

How to retrieve records of a Dataverse environment in Postman?

How to get the Dataverse Web API endpoint details in the Microsoft PowerApps?

How to create Microsoft Dynamics 365 CE Online 30 Days Trial Version?

How to create Users and Assign Security roles in Dynamics 365 CE Online?

How to load Dynamics 365 CE Online Environment faster?

How to Install, Connect to Microsoft Dataverse and Use XrmToolBox?

Comments

@apoorvaagrawal86

App Details:

Postman for Windows
Version 5.5.0
win32 10.0.14393 / x64

Issue Report:

  1. Did you encounter this recently, or has this bug always been there: Encountered this issue for the first time
  2. Expected behaviour: Running test collection with several GET and POST requests, gives 401 unauthorized error on certain iterations of the collection. Ideally, it should give 200 OK status since it executed correctly when executed individually.
  3. Console logs (http://blog.getpostman.com/2014/01/27/enabling-chrome-developer-tools-inside-postman/ for the Chrome App, View->Toggle Dev Tools for the Mac app): NA
  4. Screenshots (if applicable)

image

Steps to Reproduce —

  1. Create a collection with a GET and POST request.
  2. The test scripts include validating a data value in an object using .csv data file.
    pm.test(«CheckProductName», function() {
    var jsonData = pm.response.json();
    pm.expect(jsonData.productList[data.pId].name).to.eql(data.productName);
    });
  3. pId and productName are assigned values in a .csv data file.
  4. Run the collection runner for 6 iterations (data file has 6 iterations to be validated).
  5. On running the collection runner, the GET call starts from the 3rd iteration giving 401 unauthorized error. and the POST request call give the same error from the 5th iteration.

@sdnts

@apoorvaagrawal86 This sounds like an issue with your CSV file. Does your CSV file have enough data for all 6 iterations?
Can you keep the Postman Console (Cmd/Ctrl+Alt+C) open during the run and verify if the calls outgoing are correct?
If they are, it would point to an issue with your server. Let me know if they’re not.

@apoorvaagrawal86

Hello Sid,

Thanks for the reply. I verified the csv file and it has complete data for all the 6 iterations.

Please find the snapshot for 2 GET calls in the postman console. One returns 200 status whereas the other returns 401 status.
I am a novice in evaluating the api’s, hence please let me know what all parameters should I look to identify the correctness of an api.

image

PS — I have hidden the URLs for copyright purpose.

csv file snapshot —

image

@rustoleum76

@rustoleum76

has this been verified as a defect, yet? Should I insert my own Issue report despite my issues appearing to be the same problem as 4092? Thanks

@stefring

I‘v run into the same issue, when Runner not using the .json file, the result is fine, but with the data file upload, and there is a 401 error, have no idea how could this be ?? check in console, the head and the body is correct, don’t know why would this happen, has this been verified as a defect, and will it be fixed on the following release?

@rustoleum76

has this been verified as a defect, yet? Should I insert my own Issue report despite my issues appearing to be the same problem as 4092? What can I do to help in the investigation of this? I’d love to recommend to our management team Pro seats for this tool, but the Runner capability is a key feature that I can’t use at the moment. Thanks!

@Rob-DeRosia

I am experiencing this same issue when using NTLM authentication and multiple iterations in the Runner. Each of my collections has the Authorization request as the first request in the collection. The first two iterations succeed, but the third iteration fails with a 401 Unauthorized and the Runner immediately ends running the tests, as pictured below.

thirditeration401

After looking at the Postman Console and reviewing the request headers on the Authorization requests from each iteration, it appears that the Temporary Authentication headers are not being cleared between each run.

I am currently on the Windows client, Postman v6.0.10. Please let me know if any additional information is required to troubleshoot this issue.

@ryanhoward1988

Is there any progress on this yet? We are experiencing the same issue and are really keen to find a resolution to this.
If we can do anything to help this investigation then please let me know

@ragoutje

+1 for a solution to this issue.

It always happens on the third and further requests run in the collection runner. When running 3 or more requests from Postman one by one this does not occur.

I found that the 3rd request in the runner receives a different response header:

www-authenticate:
0:»NTLM»
1:»Negotiate»

It seems to be related.

Edit:
The 1st and 2nd requests do not receive this response header.

@andmill

+1 seeing the same recently as well whilst using runner.

@susikka

I faced this issue too. A POST request in my collection has a script. This request executed fine when run using the SEND button but returned 401 Unauthorized with collection runner.

I tried removing the script in the POST request and run the collection again. The POST request executed fine(returned 201 Created). Then I re-added the script in the request and executed the collection again and request worked again.

All other requests in the collection(that do not have any script), still return 401 Unauthorized.

These requests use OAuth2.0 for authentication.

@susikka

@madebysid Any progress on this ? Got some really urgent stuff that is stuck because of this issue. Would help if this could be resolved asap.

@shahidhafiz

I found if you don’t use inherit from parent for the authorization on each api call you get a 200 OK reliably. NTML Authentication [Beta] feel like its not stable enough.

@seancummins1

I got around this issue by changing my test.
I was getting the issue when I had my test as the below.

tests[«Status code is 200»] = responseCode.code === 200;

After changing it to the following I stopped getting the error on the 3rd iteration and all now pass.
tests[«Status code is 200»] = responseCode.code === 200 || responseCode.code === 400;

@Bakerstreetsoriginal

Facing this issue as well currently, oddly though, it’s only for the first 5 calls in the runner that use a fresh auth token.

The token is valid, I’ve double checked it in in the request headers.

@seancummins1

If you save test case then run the test case it should error because of your variables in the body. If you then run the collection it should work for all requests.

@sivcan

@ryanhoward1988

@sivcan Yes the same is happening via newman
The first 2 iterations return HTTP 200 the following iterations all return HTTP 401

@dbasargin

+1 Here.
I too am experiencing this with NTLM Authorization.

While iterating over a JSON file In the collection runner and from the command line,
after the second iteration all following requests receive a 401 unauthorized.

Postman Version is up to date: v6.7.2

I do notice: If I add NTLM Authentication headers at the Collection level, then Inherit from parent in all requests, all requests fail. If I add NTLM Authentication at the collection level and for every request in the collection, I get this behaviour where all requests in the collection for the first two iterations of my data file succeed and the rest fail.

@andmill

I’ve given up and moved to a Java framework using apache http client and testNG. Working like a charm, runs from the command line in Jenkins using maven. All open source so no yearly cost to the company from Postman enterprise. More difficult to implement but the benefits far outweigh that. For starters, it works! Also, I can validate csv and xml files easily as well as DB validation.

@numaanashraf
numaanashraf

changed the title
401 unauthorized error appears while running collection runner

401 unauthorized error for NTLM auth while running collection

Feb 1, 2019

@numaanashraf

@dbasargin

@susikka

@numaanashraf I too tried running my collection with newman. As was the case with the collection runner, with newman too only the first request was successfully executed, all others failed with HTTP 401.

This issue has been lingering for a long time now. Do we have a timeline by when we can expect this issue to be fixed ?

@andmill

@numaanashraf same here. Issues in collection runner and newman. Tried on both windows machines and Linux servers.

@harryi3t

@codenirvana I was able to reproduce this using newman too
Here’s a collection which has 1 request with NTLM auth Run in Postman

newman run -n 5 https://www.getpostman.com/collections/dd639df2a35ee6862740

harryi3t_harendras-macbook-pro____work_postman_postman-app__zsh_

@codenirvana

We’ve released a fix for this on our Canary (version: 7.1.0-canary01) channel https://www.getpostman.com/canary

Please try it out in the Canary version and let us know if you continue to face the issue.
Will update the thread once we release the fix on our stable channel.

@andmill

@codenirvana

@andmill Its fixed in the latest version of Newman as well!

@thbaid

Hi, Please clarify the version of Postman that was fixed to successfully run a collection having multiple API tests without generating 401 token issue error ? I have latest pm version and still get 401 errors .

You are up to date! Postman v7.0.7 is the latest version.

@codenirvana

@dbasargin

I tested this in the latest Canary Version. This is working nicely for me. Thank you for update. Does 7.1 have a target release date?

@codenirvana

This has been fixed in the latest Postman app.

@anandhakrishnan85

This issue still exists in latest version of Postman app (v7.10.0)

@SKvasnytsia

Hi, facing the same issue. Using NTLM Authorisation. When running Postman collection, getting 401 on the third request. Postman Version: 7.22.1

@coditva

getting 401 on the third request.

@SKvasnytsia your case seem to be similar to #7747. We’re tracking this issue. Will update there when we have a fix.


In Postman, authorization is done to verify the eligibility of a user to access a resource in the server. There could be multiple APIs in a project, but their access can be restricted only for certain authorized users.

The process of authorization is applied for the APIs which are required to be secured. This authorization is done for identification and to verify, if the user is entitled to access a server resource.

This is done within the Authorization tab in Postman, as shown below −

Authorization tab

In the TYPE dropdown, there are various types of Authorization options, which are as shown below −

Authorization options

Let us now create a POST request with the APIs from GitHub Developer having an endpoint https://www.api.github.com/user/repos. In the Postman, click the Body tab and select the option raw and then choose the JSON format.

Add the below request body −

{
	"name" : "Tutorialspoint"
}

Then, click on Send.

Authorization options1

The Response code obtained is 401 Unauthorized. This means, we need to pass authorization to use this resource. To authorize, select any option from the TYPE dropdown within the Authorization tab.

Types of Authorization

Let us discuss some of the important authorization types namely Bearer Token and Basic Authentication.

Bearer Token

For Bearer Token Authorization, we have to choose the option Bearer Token from the TYPE dropdown. After this, the Token field gets displayed which needs to be provided in order to complete the Authorization.

Step 1 − To get the Token for the GitHub API, first login to the GitHub account by clicking on the link given herewith − https://github.com/login .

Step 2 − After logging in, click on the upper right corner of the screen and select the Settings option.

Settings

Now, select the option Developer settings.

Developer Settings

Next, click on Personal access tokens.

Access Tokens

Now, click on the Generate new token button.

New  Tokens

Provide a Note and select option repo. Then, click on Generate Token at the bottom of the page.

Finally, a Token gets generated.

Generate Token

Copy the Token and paste it within the Token field under the Authorization tab in Postman. Then, click on Send.

Please note − Here, the Token is unique to a particular GitHub account and should not be shared.

Response

The Response code is 201 Created which means that the request is successful.

Code

Basic Authentication

For Basic Authentication Authorization, we have to choose the option Basic Auth from the TYPE dropdown, so that the Username and Password fields get displayed.

First we shall send a GET request for an endpoint (https://postman-echo.com/basic-auth) with the option No Auth selected from the TYPE dropdown.

Please note − The username for the above endpoint is postman and password is password.

Authentication

The Response Code obtained is 401 Unauthorized. This means that Authorization did not pass for this API.

Now, let us select the option Basic Auth as the Authorization type, following which the Username and Password fields get displayed.

Enter the postman for the Username and password for the Password field. Then, click on Send.

Username and password

The Response code obtained is now 200 OK, which means that our request has been sent successfully.

No Auth

We can also carry out Basic Authentication using the request Header. First, we have to choose the option as No Auth from the Authorization tab. Then in the Headers tab, we have to add a key − value pair.

We shall have the key as Authorization and the value is the username and password of the user in the format as basic < encoded credential >.

The endpoint used in our example is − https://postman-echo.com/basic-auth. To encode the username and password, we shall take the help of the third party application having the URL − https://www.base64encode.org

Please note − The username for our endpoint here is postman and password is password. Enter postman − password in the edit box and click on Encode. The encoded value gets populated at the bottom.

Encoded Value

We shall add the encoded Username and Password received as cG9zdG1hbjpwYXNzd29yZA== in the Header in the format —basic cG9zdG1hbjpwYXNzd29yZA ==. Then, click on Send.

Authorization

No Auth selected from the TYPE dropdown.

Authorization1

The Response code obtained is 200 OK, which means that our request has been sent successfully.

Authorization at Collections

To add Authorization for a Collection, following the steps given below −

Step 1 − Click on the three dots beside the Collection name in Postman and select the option Edit.

Collections

Step 2 − The EDIT COLLECTION pop-up comes up. Move to the Authorization tab and then select any option from the TYPE dropdown. Click on Update.

Collections1

Resolve Dataverse 401 Unauthorized Access Issue In Postman

We quite often see these 401 Unauthorized issues in Postman, even after connected to Dataverse environment and also all the required setups done in Postman.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

This issue can be due to the existing Token expiration.

Follow the below steps to regenerate the Token in Postman.

Step 1

Navigate to your collection and Click on Get New Access Token.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

Once, you get the New Access Token, you can see the below message.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

Step 2

New Token will be generated automatically and Click on Use Token to use this for executing the Web API’s.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

Step 3

Click on Access Token dropdown and Click on Manage Tokens.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

You can see all the Tokens information.

All available Tokens are displayed without a strike text and Expired Tokens are displayed with a strike text.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

Step 4 

Hover on the Expired Token, and click on Delete icon to delete it.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

Step 5

Expired Token is deleted and close the MANAGE ACCESS TOKENS popup.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

Step 6

Go back to your Web API request.

Click on Send to execute your Web API and see the results.

Resolve Dataverse 401 Unauthorized Access Issue In Postman

Hope you have successfully resolved this issue and able to connect to Dynamics 365.

Please share your valuable feedback on this article.

Понравилась статья? Поделить с друзьями:
  • Postimage ошибка 404
  • Postgresql проверка базы на ошибки
  • Postgresql ошибка целое вне диапазона
  • Postgresql ошибка ссылки между базами не реализованы
  • Postgresql ошибка синтаксиса for