简体   繁体   中英

Bearer token required for a public endpoint with axios

Using Vue.js I am trying to implement a JWT login form in a RESTful API with Spring Boot, but unless I add the bearer token to the request, all I get is a 403 status. I have set the endpoint to be accesible without any clearance, and on postman it's possible to send the request without the authorization header. This is a part of my security configuration on Spring:

.antMatchers(HttpMethod.POST, "/auth/login")
.permitAll()

And this is the vue.js service where I make the POST request:

import axios from 'axios'


let USER_API_BASE_URL = 'http://localhost:8080/auth/login/'
let config = {
    headers: {
    'Content-Type': 'application/json',
    'Authorization': "Bearer (hereGoesTheToken)"
    }}

class LoginService{
    postLogin(emailInput, passwordInput){
        let user = JSON.stringify({email: emailInput, password: passwordInput});
        var response = axios.post(USER_API_BASE_URL, user, config);
        console.log(response)
        return response
    }
}

export default new LoginService()

I want to make it so there's no need for a token in order to have access to the part where you request that same token... is there any way to do this?

I'm not 100% sure, but it seems likely your 403 is caused by CSRF protection. Check out the JWT Login sample for an example of how to enable JWT authentication on the server.

In summary, if you enable HTTP basic ( .httpBasic() ) and disable session management ( .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) ), you can also disable CSRF ( .csrf().disable() ). This would be the recommended way to achieve what you're trying to do, because a stateless server (in terms of session management) is not vulnerable to CSRF protection.

You can also implement your own endpoint for authentication, which is your example, in which case you don't need to enable .httpBasic() . You can just use .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) in that case. Check out this Tanzu Tuesday talk for more on JWT authentication (why and why not).

It is important to call out that any form of session on the server makes you vulnerable to CSRF attacks so it's important to ensure no JSESSIONID or similar is making it down to the browser. See this question and several others like it, as similar questions have been asked quite often before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM