Spring Security 4 and JSF 2 integration - spring

Is there a way to integrate Spring Security 4 (Mainly for managing user access levels and which views they can access) and JSF 2?
I found this neat thing which allows you to mix both Spring Boot, and JSF 2 with PrimeFaces 5. Great stuff. I want to see if you can kick it up another level.
Normally you would configure Spring Security for Spring MVC like so:
WebSecurityConfig.java
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("Zyst").password("password").roles("USER");
}
}
And then those would as far as I know, do correct me if I'm mistaken, look in your MvcConfig to see what it actually means by "/home" and the like:
MvcConfig.java
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
However, I've been googling for a few hours and cannot really find a conclusive answer how to configure Spring Security for JSF. Can you implement your front end using JSF and then make that managed by Spring Security, so, for example Links, ie: localhost:8080/home instead of localhost:8080/home.xhtml are properly managed and served? And so that user levels defined in WebSecurityConfig.java can only access pages relevant to themselves.
From what I've (briefly) investigated it might not be possible due to Faces and Mvc being different technologies that don't particularly play well together. However, if possible I'd like to make sure of whether it's possible or not.
And if it IS possible, can you provide either a working example, or a link to somewhere that goes more in depth? I did google quite a bit but it's 100% possible I ended up missing something.
Any and all answers are greatly appreciated.

There's no problem in using Spring Boot, Spring Security, JSF and Spring Core all together, in the end, JSF views are resolved as urls and that's what you work in Spring Security with. That's an example for the configuration in my own application, which I've pruned a bit to minimize the code amount. The code is self-explanatory:
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// Have to disable it for POST methods:
// http://stackoverflow.com/a/20608149/1199132
http.csrf().disable();
// Logout and redirection:
// http://stackoverflow.com/a/24987207/1199132
http.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.invalidateHttpSession(true)
.logoutSuccessUrl(
"/login.xhtml");
http.authorizeRequests()
// Some filters enabling url regex:
// http://stackoverflow.com/a/8911284/1199132
.regexMatchers(
"\\A/page1.xhtml\\?param1=true\\Z",
"\\A/page2.xhtml.*")
.permitAll()
//Permit access for all to error and denied views
.antMatchers("/500.xhtml", "/denied.xhtml")
.permitAll()
// Only access with admin role
.antMatchers("/config/**")
.hasRole("ADMIN")
//Permit access only for some roles
.antMatchers("/page3.xhtml")
.hasAnyRole("ADMIN", "MANAGEMENT")
//If user doesn't have permission, forward him to login page
.and()
.formLogin()
.loginPage("/login.xhtml")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/main.xhtml")
.and().exceptionHandling().accessDeniedPage("/denied.xhtml");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
//Configure roles and passwords as in-memory authentication
auth.inMemoryAuthentication()
.withUser("administrator")
.password("pass")
.roles("ADMIN");
auth.inMemoryAuthentication()
.withUser("manager")
.password("pass")
.roles("MANAGEMENT");
}
}
Of course, this code works with *.xhtml suffixed urls, as they're served by the JSF Servlet. If you want to avoid this suffix, you should use a url rewriting tool as Prettyfaces. But that's another story that has already been widely discussed in StackOverflow.
Also, remember to target your login form to the configured login processing url to let Spring Security handle the authentication and redirection to your main page. What I usually do is to use a non-JSF form and apply the Primefaces styles on it:
<form id="login_form" action="#{request.contextPath}/login" method="post">
<p>
<label for="j_username" class="login-form-tag">User</label> <input
type="text" id="username" name="username" class="ui-corner-all"
required="required" />
</p>
<p>
<label for="j_password" class="login-form-tag">Password</label>
<input type="password" id="password" name="password"
class="ui-corner-all" required="required" />
</p>
<p>
<button type="submit"
class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only">
<span class="ui-button-text">Login</span>
</button>
</p>
</form>
See also:
Spring and JSF integration
Spring Boot JSF Integration

Related

Google logout doesn't work in Windows 11 only when using spring boot security

Here is my spring boot security code. The same code works fine on Windows 10 and MacOS. But it doesn't work when I use the same code in Eclipse on Windows 11. Both Chrome and Edge browser are having the same issue. The logout button just doesn't log me out. Can anyone help? Thanks.
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**").authorizeRequests()
.antMatchers("/", "/welcome").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.and()
.logout().logoutSuccessUrl("/welcome").permitAll();
}
}
<form th:action="#{logout}" method="post">
<input type="submit" value="Sign out"/><br/>
</form>

Spring Security redirecting custom login page to itself - Too Many Redirects

I'm currently developing a custom login-page for my Spring Boot Application but I just can't get it to work. Using the default one works fine but as soon as I try to use my custom file, it just repeatedly redirects me until my Browser give up.
Other posts suggest permitting access to the login-path to erveryone but this also doesn't seem to work.
Here is my code:
WebSecurityConfig
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
And Controller for login-page
#Controller
public class WebController {
#GetMapping("/login")
public String login () {
return "login";
}
}
Any ideas what I'm missing?
You are probably using a lot of CSS and JS file link links, according to your code Spring Boot must first authenticate all the links, which is why it redirects to your login page many times.
add following code to bypass security authentication of resource link
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/bower_components/**", "/dist/**", "/plugins/**"); //write your resource directory name
}

How to configure Spring MVC HttpSecurity using Java config for login page

I am building a Spring MVC application using Java config rather than xml, with Eclipse, Maven and Spring webmvc ver 4.2.4 and Spring security 4.0.3. I have it running on Tomcat 7.
There are multiple jsp's that I can navigate from one to another, so the #RequestMappings are correct(they are listed in the configure( ) method below). I have logging set up with log4j with everything possible logged, so I can see my configurations and controllers are being called. During startup, the log file shows the mappings being set:
...RequestMappingHandlerMapping - Mapped "{[/login],methods=[GET]}"...
...RequestMappingHandlerMapping - Mapped "{[/login],methods=[POST]}" ...
My problem is the login screen does not POST to the correct method in the LoginController class when it is getting submitted, it keeps going to the "init" method which is annotated for the GET request.
Here is SecurityConfig:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/","/register","/about","/home","/demo").permitAll()
//.loginProcessingUrl("/login")
.antMatchers(HttpMethod.POST,"/login").permitAll()
.anyRequest().authenticated()
.and().formLogin().permitAll().loginPage("/login")
.and().logout().logoutUrl("/logout").invalidateHttpSession(true).logoutSuccessUrl("/home");
}
}
When //.loginProcessingUrl("/login") is uncommented, the autogenerated Spring login form appears and I can log in! So it works with the default form but not my form.
LoginController.java looks like this:
#Controller
public class LoginController {
private Logger logger = Logger.getLogger(LoginController.class);
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String init(Locale locale, Model model) {
logger.info("LoginController login INIT!");
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(#ModelAttribute LoginDTO loginObject, Locale locale, Model model) {
logger.info("LoginController login POST!");
return "home";
}
}
When the Spring default login page is submitted, it doesn't map to my LoginController. When my login.jsp is submitted, the request goes the init( ) method, not the login( ) method mapped to POST.
A snippet of my custom login.jsp I want to use instead of the default jsp:
<form:form action="${loginProcessingUrl}" method="post">
<p>
<label for="username">Username</label>
<input type="text" id="userId" name="userId"/>
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</p>
<div>
<button type="submit">Log in</button>
</div>
</form:form>
The framework is adding the CSRF token on the login page, which I can see on the browser, so that seems to be working but I'm not sure if it matters.
<input type="hidden" name="_csrf" value="ac81daad-f2e4-4357-a7a8-b7b10a67036f">
I am just learning Spring, and have been searching everywhere for some in depth explanation about how Spring Security works and is configured, especially the http object with all the chained methods. If anyone can direct me to a good reference for the latest Spring Security, I would appreciate it, or let me know what I need in my code.
From my understanding, you should remove the #RequestMapping(value = "/login", method = RequestMethod.POST) from your controller and change the security configuration as follows:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/register", "/about", "/home", "/demo").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/home")
.invalidateHttpSession(true);
}
}
Spring will automatically handles your POST request with the Spring security filter and redirects you to your login form if necessary. Please make sure your login field names are correctly named "username" and "password":
<form:form action="${loginProcessingUrl}" method="post">
<p>
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</p>
<div>
<button type="submit">Log in</button>
</div>
</form:form>
See http://docs.spring.io/spring-security/site/docs/current/reference/html/jc.html#jc-form for more information.

spring security 4 custom login page

I would like to create custom pure html/js login page in Spring Security.
I use Spring Boot 1.2.5.RELEASE
I defined an application and configuration:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#Configuration
#EnableWebSecurity
#EnableWebMvcSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("a").password("a").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // DISABLED CSRF protection to make it easier !
.authorizeRequests()
.antMatchers("/", "/login.html").permit
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.permitAll()
.and()
.logout()
.permitAll()
.logoutUrl("/logout")
.logoutSuccessUrl("/");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
My login page looks like that (copied from default page!)
<html><head><title>Login Page</title></head><body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td> </tr>
</table>
</form></body></html>
But I still have: AUTHORIZATION_FAILURE
Is it possible to create pute html login page (without jsp, thymeleaf, etc.) ?
What do I do wrong in my code ?
You configured your login page to be at /login.html (using loginPage("/login.html")). This will also change the location to which you need to post the credentials to login. The documentation states:
If "/authenticate" was passed to this method [loginPage(String)] it update the defaults as
shown below:
/authenticate GET - the login form
/authenticate POST - process the credentials and if valid authenticate the user
/authenticate?error GET - redirect here for failed authentication attempts
/authenticate?logout GET - redirect here after successfully logging out
In order to make the login work, you need to make login.html post the credentials to /login.html instead of /login.

How to configure Spring 4.0 with spring boot and spring security openId

I'm trying to get a Spring 4.0 boot application up and running with Spring Security OpenId. I'm using the standard way to bootstrap a Spring boot app:
#Configuration
#ComponentScan("x.y.z")
#EnableAutoConfiguration
#Import({SecurityConfig.class})
public class ServiceRegistryStart extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ServiceRegistryStart.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
application.sources(getClass());
return application;
}
}
The SecurityConfig.class looks like this (Influenced by the "openid-jc sample project in Spring security):
#Configuration
#EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.openidLogin()
.loginPage("/login.html")
.permitAll()
.authenticationUserDetailsService(new CustomUserDetailsService())
.attributeExchange("https://www.google.com/.*")
.attribute("email")
.type("http://axschema.org/contact/email")
.required(true)
.and()
.attribute("firstname")
.type("http://axschema.org/namePerson/first")
.required(true)
.and()
.attribute("lastname")
.type("http://axschema.org/namePerson/last")
.required(true)
.and()
.and()
.attributeExchange(".*yahoo.com.*")
.attribute("email")
.type("http://axschema.org/contact/email")
.required(true)
.and()
.attribute("fullname")
.type("http://axschema.org/namePerson")
.required(true)
.and()
.and()
.attributeExchange(".*myopenid.com.*")
.attribute("email")
.type("http://schema.openid.net/contact/email")
.required(true)
.and()
.attribute("fullname")
.type("http://schema.openid.net/namePerson")
.required(true);
}
#Bean(name = "myAuthenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
class CustomUserDetailsService implements AuthenticationUserDetailsService<OpenIDAuthenticationToken> {
#Override
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {
return new User(token.getName(), "", AuthorityUtils.createAuthorityList("ROLE_USER"));
}
}
}
The login page looks like this:
<form id="googleLoginForm" action="/j_spring_openid_security_check" method="post">
<h1>Login</h1>
<input name="openid_identifier" type="hidden" value="https://www.google.com/accounts/o8/id"/>
<input name="openid.ns.pape" type="hidden" value="http://specs.openid.net/extensions/pape/1.0"/>
<input name="openid.pape.max_auth_age" type="hidden" value="0"/>
<p>
<input name="submit" value="Login using Google" type="submit"/>
</p>
</form>
The problem is that the "/j_spring_openid_security_check" doesn't seem to exist. I think the problem is that I ought to extend from AbstractSecurityWebApplicationInitializer when using Spring Security but for boot I should use SpringBootServletInitializer. What's the best way to combine the two? The javadoc of SpringBootServletInitializer says that it registers a filter automatically when Spring Security is detected but it doesn't seem to work in this case.
I actually managed to solve this. First off all I used Spring Boot to start an embedded container so I didn't need any WebApplicationInitializers. Secondly the post URL in the login page should point to "/login/openid" and thirdly I had to disable cross-site request forgery prevention in the security configuration using:
http.csrf().disable(). ..
in the configure method in the SecurityConfig class.

Resources