Spring Boot Security without Login Form - spring

I want to add security to a Spring Boot application so I thought about using Spring Security. My only problem is the Login Form, Is there some way to authenticate a User by reading the login credentials from a config file instead of letting someone type in the name and password? I want to do that because the application will be running on a Raspberry Pi. What would be the best approach for something like that?

You can use basic authentication and pass username and password in the header.
The configuration could look like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/dashboard/**").permitAll()
.anyRequest().authenticated()
.and().httpBasic();
http.csrf().disable();
}
From the client you have to add the header:
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
The string behind Basic is the Base64 encoded username:password

Related

Keycloak Springboot bearer only for specific endpoint and non bearer for another

I am trying to use keycloak springboot adapter. I want to make some endpoints with "/api" work with bearer only to true.
But I also want the endpoint "/login" to not be a bearer only endpoint and redirect the user to the keycloak OIDC login page if he is not authenticated.
How can I achieve that ?
All I have now is just bearer only for every endpoints in my application properties.
Thanks in advance for your answers :)
In web-security conf,
enable anonymous
in http-security ant-matchers, add an entry for your public routes with permitAll()
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.anonymous();
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated();
return http.build();
}
PS
Keycloak spring adapters are deprecated
As an alternative, you can use:
spring-addons-webmvc-jwt-resource-server tutorial here
spring-boot-starter-oauth2-resource-server tutorial there (it requires more Java conf)

Spring security 5 - UsernamePasswordAuthenticationFilter and basic authentication

I'm trying to implement simple security for a small API school project and am a bit confused and overwhelmed. I followed
this blog post.
Everything works and I'm able to login and receive a jwt token. However login is currently performed by sending the username and password along with the URL as query parameters. That is of course something I would like to avoid.
I have tried adding httpbasic to the security configuration like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtAudience, jwtIssuer, jwtSecret, jwtType))
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/board/**").hasAnyRole("MEMBER", "BOARD")
.antMatchers("/members/**").hasRole("MEMBER")
.anyRequest().authenticated()
)
.httpbasic().and().
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
Login however ceases to work and I constantly get an unauthorized while trying basicAuth with postman.
So my question is: How can I change the behaviour of these code snippets to accept basic authentication and not send user credentials by URL? Do I have to override the AttemptAuthentication method too?

Configure spring security with oauth2/openid for session id but also access token

it is possible to configure spring with oauth2 to accept multiple login possibilities?
Currently I have it working with:
#Override
protected void configure(HttpSecurity http) throws Exception { // #formatter:off
http.authorizeRequests(authorizeRequests -> authorizeRequests
.anyRequest()
.authenticated())
.oauth2Login(AbstractAuthenticationFilterConfigurer::permitAll)
.addFilterAfter(new CustomAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.logout(logout -> logout.logoutSuccessHandler(oidcLogoutSuccessHandler()))
.oauth2ResourceServer().jwt();
} // #formatter:on
If one tries to access an authorize ressource, he gets redirected to a login page of an identity provider, logs in and then get a session id on the client side. The access token and the refreh token are held into memory on the server side.
But now I also want to use an access token to access ressources.
But when I do this, the security application context is just null.
What do I have to do?
I have searching in the doc but could not understand how to achieve this.
I would expect to just add in application.properties:
spring.security.oauth2.resourceserver.jwt.jwk-set-uri
And to add:
.oauth2ResourceServer().jwt() to my HttpSecurity but this does not do the work.
Found the answer, if Bearer is not set as prefix in the Authorization header when sending the token, then it will not be recognized.
Kind of normal since it is the standard...

Getting [invalid_id_token] Missing (required) ID Token in Token Response for Client Registration: github

I'm using SpringBoot and Oauth2 to authenticate on my application, using github for now.
If I use the scope oidc on application.properties the process works fine and github is used for he login.
My issue is that I want/need to use scope openid to get the id_token. When I change my application.properties to
spring.security.oauth2.client.registration.github.scope=openid
I start getting this error as response from login:
[invalid_id_token] Missing (required) ID Token in Token Response for Client Registration: github
I still get the http://localhost:8080/login/oauth2/code/github?code=ABC&state=CDE but right after that, the error shows up.
My security class is:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.oauth2Login()
;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("springuser").password(passwordEncoder().encode("spring123")).roles("USER")
.and()
.withUser("springadmin").password(passwordEncoder().encode("admin123"))
.roles("ADMIN", "USER");
}
Any clue on what I should look to?
Thanks in advance
This
spring.security.oauth2.client.registration.github.scope=openid
activates OpenID Connect authentication, that's built on top of Oauth2.
But that's no longer just Oauth2, as it requires that token.
If Oauth2 is what you want, just remove the above line.
Yes it's just confusing, and that's probably why folks avoid OIDC.
I got it working!
Turns out the issue wasn't on the code. Problem was somehow on the github oauth2 credentials. When I used a token/secret generated by Google Credentials I didn't have to change anything else besides the application.properties.
The mistery about github login still remains, since there's not much data on the token register to be changed.

how to implement a authentication with spring boot security?

i am using spring boot. i want to post a username and password params to login, and if login success then return a token. after, i will use the token to judge login status. here is my security configure code. but i don't konw where to write the login authentication logic code.
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.fullyAuthenticated()
.and()
.formLogin()
.loginPage("/user/unlogin")
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/user/login")
.antMatchers("/user/logout")
.antMatchers("/user/register");
}
}
==========================
thank you !
There's always more than one way to do something with Spring. There is a happy path (probably) with Spring Boot, and you seem to have started on it. Note though, if you want Boot to provide some default behaviour, then don't use #EnableWebSecurity (as advised in the user guide). The web-secure sample has an example you can follow.
If you use formLogin() the default login URL is /login (not /user/login), so you should be able to post the username and password to that endpoint to authenticate. Don't add /login to the unsecured paths using web.ignoring() or Spring Security will never process it. When you post to /login you get back a JSESSIONID cookie. That's your authentication token, and it expires when the session expires in the server (30min by default, but easily configurable). Include it in future requests for secure resources - some HTTP clients will even do that for you (like a browser does).

Resources