I am using Basic authorization in my Springboot project. Once I successfully login, I can inspect the backend webpage and see that there is an Authorization
with the value Basic YmNyeX323G5yb2xsdGVjaC5jb206cyE5c2RzZA
in the Network
tab.
I can then use the value Basic YmNyeX323G5yb2xsdGVjaC5jb206cyE5c2RzZA
to make requests via Postman to the server by setting that value as the Authorization
value.
So, my question is, how can I return this value after logging in?
This is my SecurityConfiguration.java
file:
@Configuration
@EnableConfigurationProperties
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
MongoUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/", "/register").permitAll().anyRequest().authenticated()
.and().logout(logout -> logout
.permitAll()
.clearAuthentication(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID"))
.httpBasic()
.and().sessionManagement().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService);
}
What would the end point look like that can return the basic authorization token mentioned above?
CodePudding user response:
You don't, simply because that is not how Basic Authentication works.
The "token" (or rather header) is build on the client and sent to the server. The token is nothing more than the username and password separated by a :
and then Base64 encoded. This is part of the HTTP standard and is just provided/done by the browser. So after entering the username / password your browser will create an Authorization
consisting of that encoded token.
So you entered
username: bcry}nrolltech.com
password: s!9sdsd
which becomes YmNyeX323G5yb2xsdGVjaC5jb206cyE5c2RzZA
( bcry}nrolltech.com:s!9sdsd
encoded in Base64). Which is send to the server as Authorization: YmNyeX323G5yb2xsdGVjaC5jb206cyE5c2RzZA
. Which can use the reverse process to decode it. (Just as I did to retrieve the username/password).
The token is then decoded on the server, split on the ;
and the seperated username and password are passed to the authentication mechanism for validation.
So it isn't the server that is generating this "token" nor is it a token but merely the encoded username and password.
There is more in-depth information on WikiPedia on how Basic Authentication works. RFC2617 and RFC7617 describes the protocol in great detail.
CodePudding user response:
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
Object details = authentication.getDetails();
Try this, it might be useful, token in details