Spring Web Security logout not working with httpBasic authentication - java

I'm using basic authentication to secure an initial REST web service that I'm working on. Everything seems to work okay, except the logout path does not seem to work. It redirects to "/login?logout", as documented, but my user does not seem to actually be logged out. (ie. I can still access page X and not page Y as expected).
Application config:
#Configuration
#ComponentScan
#EnableAutoConfiguration(exclude = ManagementSecurityAutoConfiguration.class)
#EnableWebSecurity
#EnableSwagger
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
#Configuration
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and().authorizeRequests().antMatchers("/manage/**").hasRole("ADMIN")
.anyRequest().fullyAuthenticated()
.and().logout().permitAll().logoutRequestMatcher(new AntPathRequestMatcher("/logout", HttpMethod.GET.toString())).invalidateHttpSession(true);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN", "USER").and().withUser("user").password("user").roles("USER");
}
}
}
Please note that security in general looks to be working. I can open a new incognito tab and the authentication / security works as expected.

You cannot logout from basic http authentication with a logout link.
Please check a similar thread here.

Related

Spring Boot Active Directory Authentication Not Redirecting After Succesful Login

I am trying to create a web page accessible through active directory authentication. I successfully connect and can authenticate credentials. When an incorrect log in is submitted the terminal prints: Active Directory authentication failed: Supplied password was invalid. Nothing prints in the terminal on correct credentials.
The problem is after I 'successfully' log in the web page is not shown. Instead, the log in window continually shows up and does not redirect. How do I get to the web page after credentials are authenticated? Below is the code I'm using.
ADConfig.java
#Configuration
#EnableWebSecurity
public class ADConfig extends WebSecurityConfigurerAdapter {
#Value("${ad_domain}")
private String AD_DOMAIN;
#Value("${ad_url}")
private String AD_URL;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
ActiveDirectoryLdapAuthenticationProvider adProvider =
new ActiveDirectoryLdapAuthenticationProvider(AD_DOMAIN, AD_URL);
adProvider.setConvertSubErrorCodesToExceptions(true);
adProvider.setUseAuthenticationRequestCredentials(true);
auth.authenticationProvider(adProvider);
auth.eraseCredentials(false);
}
}
Controller.java
#RestController
public class Controller {
#GetMapping("/")
public String index() {
return "home page";
}
}
App.java
#Configuration
#SpringBootApplication
public class App {
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}

Login Form in Oauth2 server doesn’t return to the Client url

I’m writting an Oauth2 application.
The Spring application is :
#SpringBootApplication
#EnableAuthorizationServer
#EnableResourceServer
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
the application.properties is
security.oauth2.client.client-id=jerpweb
security.oauth2.client.client-secret=implementa
security.oauth2.client.authorized-grant-types=password,client_credentials,authorization_code,refresh_token
security.oauth2.client.scope=openid
security.oauth2.client.auto-approve-scopes=.*
and the securityConfiguration is:
#Configuration
#EnableWebSecurity
#EnableTransactionManagement
#Order(-5)
public class SecurityConfigurationOauth extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailServiceImpl userService;
#Autowired
private PasswordEncoderService passwordEncoder;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll();
}
}
The oauth server is working with protocol password ( localhost:8081/oauth/token).
if I use an oauth2 client
#SpringBootApplication
#EnableOAuth2Sso
public class ApplicationUi {
public static void main(String[] args) {
SpringApplication.run(ApplicationUi.class, args);
}
}
security.oauth2.client.client-id=jerpweb
security.oauth2.client.client-secret=implementa
security.oauth2.client.access-token-uri=http://localhost:8081/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:8081/oauth/authorize
security.oauth2.client.token-name=oauth_token
security.oauth2.client.authentication-scheme=query
security.oauth2.client.client-authentication-scheme=form
security.oauth2.client.scope=openid
the client is redirected to the authorization server correctly but if the authentication is successfull doesn't come back to the client.
I.e. if I call page localhost:8080/ I got redirected to http://localhost:8081/login but if the authentication is ok the browser remains on page ttp://localhost:8081/login instead of returning to page localhost:8080/.
What is the correct configuration of SecurityConfiguration with
an oauth2 login form?
The securityConfiguration is OK the problem is how the authorization server is set up.
For some reasons authorization server must have a context-path so the correct configuration for server application.properties is:
server.port=8081
server.servlet.context-path=/uaa
security.oauth2.client.client-id=jerpweb
security.oauth2.client.client-secret=implementa
security.oauth2.client.authorized-grant-types=password,client_credentials,authorization_code,refresh_token
security.oauth2.client.scope=openid
security.oauth2.client.auto-approve-scopes=.*
the client mapping must be changed accordingly
auth-server=http://localhost:8081/uaa
security.oauth2.client.access-token-uri=${auth-server}/oauth/token
security.oauth2.client.user-authorization-uri=${auth-server}/oauth/authorize
security.oauth2.resource.user-info-uri=${auth-server}/api/userinfo
With these modifications in place redirect works fine.

Spring Boot Startup Analysis Tool

I am trying to use this tool on github to analyze my spring boot app's startup time. Here's my main class:
#Configuration
#EnableAutoConfiguration
#ComponentScan(lazyInit = true, value = {"com.test.app","com.github.lwaddicor.springstartupanalysis"})
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ApiApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
My application starts up fine but when I try to navigate to: http://localhost:8080/spring-startup/ I get the following message:
{"status":401,"message":"Authentication failed","errorCode":10,"timestamp":1519416149986}
I tried editing the security filters like so:
#EnableWebSecurity
#EnableWebMvc
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(,
"/configuration/ui",
"/configuration/security",,
"/spring-startup",
"/webjars/**");
}
}
But that didn't work. Any ideas what I'm doing wrong?
I think antMatchers() alone is not sufficient since you just tell the system which resources are affected but you do not specify how to deal with them. Append .permitAll() and it should work.
I am using something like this:
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.HEAD, "/**").permitAll()
.antMatchers("/v2/api-docs", "/configuration/ui", ...)
.permitAll()
.antMatchers(basePath + "/**").authenticated()
...
basePath is the path to the rest api which should be secured.
I got this to work by commenting out the overriden configure method. Not optimal but I only need to run this locally once so not a big deal to turn security off either.

Dynamically Configure LDAP Server using Spring Security

The Spring Security Tutorial has an example of configuring an LDAP Server:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
#Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource().ldif("classpath:test-server.ldif");
}
}
}
However, I'm looking for a way to initialize the the LDAP server dynamically, not in the configuration file. I can't seem to find any examples. The purpose of this is to implement SSO for a login form.
I found it easier to work with a lower-level directory, ldaptive, to solve this problem.

Java spring Rest and Android

I have rest service with java back-end. i use Spring Security. What steps do I need to do in order to make authorization available to Android apps?
At the moment all works in the web version. This is Spring Security config.
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
AuthenticationService authenticationService;
#Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
// отключена защита csrf на время тестов
http.csrf().disable().addFilterBefore(filter,CsrfFilter.class);
http.authorizeRequests().antMatchers("/account/**").hasRole("USER")
.antMatchers("/user/**").hasRole("ADMIN")
.and().formLogin();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(authenticationService);
}
P.S. Or any steps to do and no matter who acts as the client.
(i can authonticate via postman) I'm interested in the approach, whether it is necessary separately to implement in order to log in via the Android app was possible?

Categories

Resources