Spring boot 1.5.1 update static content 404 - java

This configuration works with boot 1.4.3.RELEASE
my static content works perfectly.
When i change the version to 1.5.1.RELEASE my static content returns
404 not found.
#Configuration
#EnableWebMvc
public class AppWebConfiguration extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/resources/**").addResourceLocations("file:" + Paths.get(System.getProperty("user.home"), SGISSConfig.getInstance().getRepoFolder()) + "/");
}
Security Class
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/email/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
#Autowired
private UserDetailsService users;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(users).passwordEncoder(new BCryptPasswordEncoder());
}
#Override
public void configure(WebSecurity web) throws Exception{
web.ignoring().antMatchers("/static/**");
}
}
My static resources are /resources/static/**
Edit
Folder structure

Related

Spring boot login keycloak

My configuration in spring boot always redirect to login form keycloak.
i don't want to login with keycloak form.
i want to login to keycloak with my form login, how can I solve my problem?
this is my config:
#Configuration
public class SecurityConfig {
#Bean
protected SessionRegistry buildSessionRegistry() {
return new SessionRegistryImpl();
}
#Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
#KeycloakConfiguration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public static class KeycloakConfig extends KeycloakWebSecurityConfigurerAdapter {
#Autowired
SessionRegistry buildSessionRegistry;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable();
http.authorizeRequests().anyRequest().authenticated();
http.sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and()
.addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter(), LogoutFilter.class)
.addFilterAfter(keycloakSecurityContextRequestFilter(),
SecurityContextHolderAwareRequestFilter.class)
.addFilterAfter(keycloakAuthenticatedActionsRequestFilter(),
KeycloakSecurityContextRequestFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and().logout()
.addLogoutHandler(keycloakLogoutHandler())
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");
}
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(buildSessionRegistry);
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/img/**", "/js/**", "/css/**");
}
}
}

CSS resources blocking by Spring Security for non authorized requests

I'm using spring boot, my CSS resources are located in .../src/main/resources/static and i have WebSecurityConfig class:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/registration", "/static/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
and MvcConfig class:
#Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
When i logged in css resources are activated.
I have access to my templates when i'm not logged in.
Why CSS resources blocking for non authorized request?
Sorry for my English. I'll very grateful for your help!
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/control").hasRole("ADMIN")
.antMatchers("/register", "/login_auth", "/login").permitAll()
.antMatchers("/img/*.jpg", "/*.js", "/*.css").permitAll()...
i did this to access the files in the root static folder.
if you got em under folders do this instead:
.antMatchers("/img/**", "/js/**", "/css/**").permitAll()

How to implement about getting current user information from server when using spring security while i access user information from android client

This is the JSON that I returned after logging in:
{
"access_token":"41208e01a-f26c-4167-9fc9-d16730022056",
"token_type": "bearer",
"refresh_token": "3808e00a-896c-8067-18c9-736730022032",
"expires_in": 25348,
"scope": "read write",
"jti": "6f08e00a-d26c-4067-8fc9-c16730022028"
}
I want to get current user information by using this url:https://localhost:8080/user/getuserinfo?access_token=41208e01a-f26c-4167-9fc9-d16730022056 from android client,i meant that how to implement requirement on server and this is my Configuration:how can i use spring security & oauth2 to realize the purpose about redirecting to different login pages when user use different terminal browser?
I change my spring SecurityConfig,here is used to processing some authorizeUrls:
#Configuration
#Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends GlobalAuthenticationConfigurerAdapter {
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
//doing jdbc Authentication
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
#Configuration
#Order(1)
public static class ClientSecurityConfigurationAdapter extends
WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/mobile/**")
.formLogin().loginPage("/client/login")
.loginProcessingUrl("/oauth/login")
.successHandler(clientLoginSuccessHandler).permitAll()
.and()
.logout()
.logoutSuccessHandler(clientLogoutSuccessHandler)
.logoutUrl("/client/logout")
.logoutSuccessUrl("/client/login")
.invalidateHttpSession(true);
}
}
#Configuration
#Order(2)
public static class WebSecurityConfigurerAdapter extends
WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.regexMatcher("/((?!api).)*")
.formLogin()
.loginPage("/web/login")
.loginProcessingUrl("/oauth/login")
.successHandler(loginSuccessHandler)
.permitAll()
.and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler)
.logoutUrl("/web/logout")
.logoutSuccessUrl("/web/login")
.invalidateHttpSession(true);
}
}
}
and add ResourceServerConfig for handle token validation issues:
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
TokenStore tokenStore;
#Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/api/**").//
and().authorizeRequests().antMatchers("/api/**",).authenticated();
}
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("openid").tokenStore(tokenStore);
}
}
finally,build a request with a request header
"Authorization:Bearer <access_token>"

Spring default login page not found

Here is my security configuration:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private UserDetailsServiceImpl userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/admin").hasAnyAuthority("ROLE_ADMIN")
.anyRequest().permitAll();
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){ return new BCryptPasswordEncoder(); }
I expected to see the default login page at /login, but I got 404 error. What may be wrong with my configuration?
Here is the solution
http://docs.spring.io/spring-security/site/docs/current/guides/html5/hellomvc-javaconfig.html#registering-spring-security-with-the-war
I did not declare required MessageSecurityWebApplicationInitializer class.

No Such Client Exception Spring Oauth2

I am trying to implement Spring Security OAuth2 using Java config.
My usecase requires the use of password grant_type.
I have configured this so far without the need for a web.xml and would prefer to keep it that way
Versions I am using:
Spring Framework: 4.1.6
Spring Security: 4.0.1
Spring Security OAuth:2.0.7
To make explaining this easier I have enabled GET on the token endpoint
#Override
public void configure
(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET); //<-- Enable GET
}
The request that I am making is as follows:
http://localhost:8080/project/oauth/token?
client_id=testClient&
grant_type=password&
username=user&
password=password
The header includes an Authorization header that contains the encoded version of:
Username: user
Password: password
The exception I get is:
HTTP Status 500 - Request processing failed; nested exception is
org.springframework.security.oauth2.provider.NoSuchClientException:
No client with requested id: user
From the exception description it appears that OAuth is looking in the ClientDetailsService for the client: user. However user is a user credential. I am obviously missunderstanding something about the configuration.
My configuration is as follows;
ServletInitializer.java
public class ServletInitializer extends AbstractDispatcherServletInitializer {
#Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.scan(ClassUtils.getPackageName(getClass()));
return context;
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException{
super.onStartup(servletContext);
DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(null, false, "/*");
}
}
WebMvcConfig.java
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception{
auth.
inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/Services/*")
.authenticated()
.and()
.httpBasic();
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
OAuth2ServerConfig.java
#Configuration
public class OAuth2ServerConfig {
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter{
#Autowired
private TokenStore tokenStore;
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
clients
.inMemory()
.withClient("testClient")
.secret("secret")
.scopes("read", "write")
.authorities("ROLE_CLIENT")
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(60)
.refreshTokenValiditySeconds(3600);
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception{
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
}
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources){
resources.resourceId("SomeResourseId").stateless(false);
}
#Override
public void configure(HttpSecurity http) throws Exception{
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.authorizeRequests()
.antMatchers("/secure/**").access("#oauth2.hasScope('read')");
}
}
}
Code in gitrepo for ease of access: https://github.com/dooffas/springOauth2
I'm not sure where the 500 comes from in your case. I see a 406 because there is no JSON converter for the access token (Spring used to register one by default for Jackson 1.* but now it only does it for Jackson 2.*). You token endpoint works for me if I add jackson-databind to the classpath, e.g.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
<scope>runtime</scope>
</dependency>
This works for me:
$ curl -v testClient:secret#localhost:8080/oauth/token?'grant_type=password&username=user&password=password'
P.S. you really ought not to use GET for a token request.
You have defined different authorities
try this:
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception{
auth.
inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER", "CLIENT");
}
And add param grant_type=password to your request

Categories