Spring Boot and Thymeleaf Resource folder Issue - spring

I am trying to set resource folder in my Spring Boot project. But not able to make it. Please help. I am trying to integrate thymeleaf.
I am able to get index.html
But I am not able to include resource /css/mobile-angular-ui-desktop.min.css file in index.html.
It give me 404 Page Not found error.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Provision Admin</title>
<link rel="stylesheet" th:href="#{/css/mobile-angular-ui-base.min.css}"
href="../static/css/mobile-angular-ui-base.min.css" />
<link rel="stylesheet"
href="/css/mobile-angular-ui-desktop.min.css" />
<script type="text/javascript">
var appContext = '/profilebatch';
</script>
</head>
<body>
</body>
</html>
I setting following security.
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends
WebSecurityConfigurerAdapter {
#Autowired
private SecurityProperties security;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/css/**")
.permitAll().antMatchers("**/favicon.ico").permitAll()
.antMatchers("/secure/**").fullyAuthenticated().and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.permitAll().and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
}
#Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user")
.roles("USER").and().withUser("admin").password("admin")
.roles("ADMIN");
}
}

Finally things are working fine.
I removed #EnableWebMvc in my configuartion.

you don't have th:href for desktop, if you can access base so this is your problem:
th:href="#{/css/mobile-angular-ui-desktop.min.css}"

Static resources default place at /public instead of /src/main/resources/static

Related

Custom login with Spring Security and OAuth2

I am trying to customize login behavior in my Spring Boot app.
The security configuration of my app is as follows:
#EnableWebSecurity
#Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final CustomAuth2UserService customAuth2UserService;
public SecurityConfiguration(CustomAuth2UserService customAuth2UserService) {
this.customAuth2UserService = customAuth2UserService;
}
#Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/bundle.js")
.antMatchers("/slds-icons/**")
.antMatchers("/assets/**")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/**")
.antMatchers("/swagger-resources")
.antMatchers("/v2/api-docs")
.antMatchers("/api/redirectToHome")
.antMatchers("/test/**");
}
public void configure(HttpSecurity http) throws Exception {
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
private RegexRequestMatcher requestMatcher =
new RegexRequestMatcher("/api/", null);
#Override
public boolean matches(HttpServletRequest request) {
return requestMatcher.matches(request);
}
};
http.csrf()
.requireCsrfProtectionMatcher(csrfRequestMatcher)
.and()
.authorizeRequests()
.antMatchers("/oauth2login").permitAll()
.antMatchers("/manage/**").permitAll()
.antMatchers("/entry-point").permitAll()
.antMatchers("/oauth2/*").permitAll()
.antMatchers("/api/auth-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.anyRequest().authenticated()
.and()
.oauth2Login().loginPage("/oauth2login")
.defaultSuccessUri("/")
.userInfoEndpoint()
.userService(customOAuth2UserService);
http.cors().disable();
}
}
The custom OAuth2 user service is as follows:
#Component
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private UserRepository userRepository;
private RoleUserEmailMapRepository roleUserEmailMapRepository;
...
#Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) {
DefaultOAuth2User oAuth2User = (DefaultOAuth2User) super.loadUser(userRequest);
Collection<GrantedAuthority> authorities = new HashSet<>(oAuth2User.getAuthorities());
Map<String, Object> attributes = oAuth2User.getAttributes();
...
}
}
The OAuth controller is as follows:
#Controller
public class OAuthController {
private final Logger log = LoggerFactory.getLogger(OAuthController.class);
#GetMapping("/oauth2login")
public String signIn(Model model) {
log.info("Sign in!!");
model.addAttribute("email",
"");
return "first-page";
}
}
first-page.html is as follows:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Enter email</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container my-5">
<div class="row">
<div class="col-md-6">
<form th:action="#{/redirect-to-auth-provider}" method="post">
<div class="row">
<div class="form-group col-md-6">
<label for="email" class="col-form-label">Email id</label>
<input type="text" th:value="${email}" class="form-control" id="email" placeholder="Email">
</div>
</div>
<div class="row">
<div class="col-md-6 mt-5">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
OAuth client config properties are as follows:
spring.security.oauth2.client.registration.abc-auth.client-id=123456
spring.security.oauth2.client.registration.abc-auth.client-name=Auth Server
spring.security.oauth2.client.registration.abc-auth.scope=api
spring.security.oauth2.client.registration.abc-auth.provider=abc-auth
spring.security.oauth2.client.registration.abc-auth.client-authentication-method=basic
spring.security.oauth2.client.registration.abc-auth.authorization-grant-type=authorization_code
myapp.oauth2.path=https://abc-auth.com/services/oauth2/
spring.security.oauth2.client.provider.abc-auth.token-uri=${myapp.oauth2.path}token
spring.security.oauth2.client.provider.abc-auth.authorization-uri=${myapp.oauth2.path}authorize
spring.security.oauth2.client.provider.abc-auth.user-info-uri=${myapp.oauth2.path}userinfo
spring.security.oauth2.client.provider.abc-auth.user-name-attribute=name
The Auth provider controller is as follows:
#Controller
public class AuthProviderController {
private final Logger log = LoggerFactory.getLogger(AuthProviderController.class);
#Autowired
private OAuth2ClientProperties properties;
Map<String, String> oauth2AuthenticationUrls
= new HashMap<>();
#RequestMapping(value = "/redirect-to-auth-provider", method = RequestMethod.POST)
public ModelANdView entryPoint(String email) {
log.info("EMAIL RECEIVED AS PART OF REQUEST PARAM = " + email);
List<ClientRegistration> clientRegistrations = new ArrayList<>(
OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());
String authorizationRequestBaseUri
= "oauth2/authorization/";
String tenantName = email.split("#")[1];
log.info("DERIVED TENANT NAME = " + tenantName);
clientRegistrations.forEach(registration -> //FOR TESTING, HARD-CODED THE VALUES
oauth2AuthenticationUrls.put("abc.com",
authorizationRequestBaseUri + "abc-auth"));
return new ModelAndView("redirect:" + oauth2AuthenticationUrls.get("salesforce.com"));
}
}
Now while I am browsing the end-point of my app: https://localhost:4060(existing end-point of my app), it's successfully redirecting to https://localhost:4060/oauth2login, where I am able to enter email id.
On submit of email id, in the browser network tab, I am seeing: /redirect-to-auth-provider end-point getting invoked, and the following three sequences of calls are happening as expected:
1. https://localhost:4060/oauth2/authorization/abc-auth
2. https://abc-auth.com/services/oauth2/authorize?response_type=code&client_id=123456&scope=api&state=qKPaLcuCp5vtXPlZDQMFKA7Qe4wLApFKtaPB9HOIN0M=&redirect_uri=https://localhost:4060/oauth2
3. https://localhost:4060/oauth2?code=abcdef&state=qKPaLcuCp5vtXPlZDQMFKA7Qe4wLApFKtaPB9HOIN0M=
But, at the end of this call chain, after successful authentication, it's again redirecting to the same page: https://localhost:4060/oauth2login. I want the behavior as, the user gets authenticated properly and after successful authentication, the user should no longer get redirected to https://localhost:4060/oauth2login.
To my surprise, it's working perfectly fine, when I am NOT customizing the login behavior. Then post-authentication, the user is redirected to the home page i.e. https://localhost:4060, and able to properly use the app.
I am not able to figure out what I am missing here.
As I mentioned in an earlier comment, I recommend focusing on a minimal example of your specific problem, instead of a complex application. It helps to learn those basics in small pieces, and it helps us help you more easily if you have a minimal example.
The concept in play here is customizing the redirect_uri. You'll want to thoroughly review the entire section of the docs on OAuth2 Login, specifically the section on the Redirection Endpoint.
It's difficult to tell, but it looks as though you have somehow customized the redirect_uri for the abc-auth client. In order to make this work, you'll need to instruct the OAuth2LoginAuthenticationFilter to use your customized redirect_uri, as in the following example:
#EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Login(oauth2 -> oauth2
.redirectionEndpoint(redirection -> redirection
.baseUri("/oauth2/*")
...
)
);
}
}
Note, the actual endpoint for abc-auth will be /oauth2/abc-auth, not /oauth2. It is essential that you have a unique redirect_uri for each oauth client, so you are not vulnerable to attacks such as mix-up (see our SpringOne 2021 presentation for more on this).
As the docs state, you'll also need a property to set your client registration to match:
spring.security.oauth2.client.registration.abc-auth.redirect-uri={baseUrl}/oauth2/{registrationId}

display spring security authentication object when SessionCreationPolicy.STATELESS

#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
MyUserDetailsService myUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/index").permitAll();
http.authorizeRequests().antMatchers("/main").permitAll();
http.formLogin().loginPage("/login").permitAll().successHandler(successHandler());
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Session is STATELESS
}
I set spring security sessionpolicy to STATLESS
because I'm using JWT so that STATLESS would be better
but STATELESS cause one problem
it's impossible to dispaly authentication object in thymeleaf
<h1>[[${#authentication }]]</h1>
if I changed session policy I could display authentication object
but but that's not what i want
in short
can i use authentication object with thymeleaf when spring's session policy is STATELESS
Form based log in requires a session, so marking as stateless would mean that the user is not available. Likely you can see the page because it is marked as permitAll which means no user is necessary to see it.
To fix this, you can switch to a form of authentication that is stateless too (i.e. it is included in every request). For example:
// #formatter:off
http
.authorizeRequests()
.mvcMatchers("/index", "/main").permitAll()
.and()
.httpBasic()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// #formatter:on
I'm also not sure about the syntax the themleaf template is using. For me, I use something like this:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Test</title>
</head>
<body>
<h1 th:text="${authentication?.name}"></h1>
</body>
</html>
Then I use the following to expose the Authentication as a model attribute:
#Controller
public class IndexController {
#GetMapping("/")
String index() {
return "index";
}
#ModelAttribute
Authentication authentication(Authentication authentication) {
return authentication;
}
}
I have a test that validates it works
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoApplicationTests {
#Autowired
TestRestTemplate rest;
#Test
void indexWhenAnonymous() throws Exception{
ResponseEntity<String> result = rest.exchange(RequestEntity.get(URI.create("/")).build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody()).doesNotContain("user");
}
#Test
void indexWhenAuthenticated() throws Exception{
ResponseEntity<String> result = rest.exchange(RequestEntity.get(URI.create("/")).headers(h -> h.setBasicAuth("user", "password")).build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody()).contains("user");
}
}
You can find the complete sample at https://github.com/rwinch/spring-security-sample/tree/display-auth-stateless-thymeleaf which allows log in with the username user and password password.

Spring Boot doesn't load javascript file

After Spring starts, I open my ajax.html page, but nothing happens. There is no error message, the js file just doesn't start. If I write javascript-code in ajax.html, it works normally.
ajax.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" xmlns:c="http://xmlns.jcp.org/xml/ns/javaee">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript"
src="webjars/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="../static/js/main.js"></script>
</head>
<body>
<div id="fill">
</div>
</body>
</html>
project structure
enter image description here
I had the same issue, and solved it in the following way:
I added the addResourceHandlers to my Java config file:
#Configuration
#EnableWebMvc
#ComponentScan
public class WebConfig implements WebMvcConfigurer {
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**", "/js/**")
.addResourceLocations("classpath:/static/css/", "classpath:/static/js/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
resources folder contains a static/js and a static/css folder both containing the specified files.
Hope it gives you help!
Have you added the resource handler for webjars? See: https://www.baeldung.com/maven-webjars
../static/js/main.js seems wrong. In spring boot, resources in the static directory are referred to without "static" in the URL, so just /js/main.js.
Other than that, are the scripts being loaded? What does the Network tab for the Console say?
As you are using Spring boot, you don't have to add "/static/**" folder in your url. You should miss "/static/" and write like this:
<script type="text/javascript" src="/js/main.js"></script>
And make sure that if you are using spring securiry, you should permit All to access "/js/**" path :
http
.csrf().disable()
.authorizeRequests()
.antMatchers( "/js/**", "/css/**")
.permitAll()
.anyRequest()
.authenticated();

Spring Boot and Security Dynamic Authentication and Authorization

I am going to develop a login page using spring boot and security which users and roles can be created by admin so the system can have many roles and users...also admin can assign the roles to users and remove them as well.
I have used good samples of how to implement it but after reading so much doc and tutorials still having below questions and don't know what is the best practice to implement spring security and boot together.tried to move on debug mode to find out what is happening behind the scene step by step.
my assumption was for each and every http request application refers to WebSecurityConfig class to check the access but surprisingly it was not like that and fellow was as below.seems application goes to config class once at the beginning and every things populates.bootstrap doing so many actions in background and it made me confuse and can't understand the relation between the classes.
configureGlobal-->configure-->whatever you write as a URL it goes to /login) -->controller (login method) --> submit the form with user/pass --> loadUserByUsername --> controller (welcome method) --> welcome.jsp
1-what exactly configureGlobal and configure do when the application loads?
2-what is the exact role of AuthenticationManagerBuilder?
3-how spring security knows to send the user/pass after form submition to loadUserByUsername method?
4-loadUserByUsername return user object to where? because when methods reach to the end it redirects to controller welcome method and it send you to welcome method when username and password is correct.
4-how to use grantedAuthorities to re-direct the user based on his role to different pages?
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<title>Log in with your account</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/common.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form method="POST" action="${contextPath}/login" class="form-signin">
<h2 class="form-heading">Log in</h2>
<div class="form-group ${error != null ? 'has-error' : ''}">
<span>${message}</span>
<input name="username" type="text" class="form-control" placeholder="Username"
autofocus="true"/>
<input name="password" type="password" class="form-control" placeholder="Password"/>
<span>${error}</span>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
<h4 class="text-center">Create an account</h4>
</div>
</form>
</div>
<!-- /container -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
WebSecurityConfig Class
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/registration").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
UserDetailsServiceImpl class
#Service
public class UserDetailsServiceImpl implements UserDetailsService{
#Autowired
private UserRepository userRepository;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
}
}
UserController Class
#Controller
public class UserController {
#Autowired
private UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.save(userForm);
securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
#RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
I would like to share the answer of some questions which are clear to me now.
when you start your project , first of all it goes to WebSecurityConfig class and look for configureGlobal method to build the authentication process and then looks for configure method to set the security.
AuthenticationManagerBuilder is a class with many methods like userDetailsService which is used to authenticate based on user details so when you login it will sends the credentails to a class which has implemented UserDetailsService interface.
A POST to the /login URL will attempt to authenticate the user so configureGlobal will do the needful.
It has called from configureGlobal method and is returned backed there and still everything is in root path so will find the proper method in controller class.
AuthenticationSuccessHandler can help in this regard.

Spring security http basic auth for Rest api with Java config

I am trying to secure a CXF based rest API with Spring security. While my configuration technically works, I cannot seem to get the API to respond with JSON rather than an HTML message upon 401. Based on a few other SO posts I put together the following java config, using groovy, for the spring security configuration:
#Configuration
#EnableWebSecurity
#Slf4j
class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) {
http.antMatcher('/api/**')
.authorizeRequests()
.antMatchers('/api/admin/**').hasRole('ADMIN')
.antMatchers('/api/**').hasRole('USER')
.and()
.httpBasic()
.and()
.addFilterBefore(
new BasicAuthenticationFilter(authenticationManager: authenticationManager(), authenticationEntryPoint: new BasicJsonEntryPoint(realmName: 'Local')),
BasicAuthenticationFilter.class
)
}
static class BasicJsonEntryPoint extends BasicAuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest req, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
log.debug 'Handling response'
response.addHeader HttpHeaders.WWW_AUTHENTICATE, /Basic realm="${getRealmName()}"/
response.setStatus HttpStatus.UNAUTHORIZED.value()
response.getWriter().println([status: HttpStatus.UNAUTHORIZED.value(), message: e.getMessage()].toJson())
}
}
}
I've tried numerous variations on this general approach, but no matter what I get HTML back from the API. See the following req/resp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 401 Full authentication is required to access this resource</title>
</head>
<body>
<h2>HTTP ERROR 401</h2>
<p>Problem accessing /api/test. Reason:
<pre> Full authentication is required to access this resource</pre>
</p>
<hr />
<i>
<small>Powered by Jetty://</small>
</i>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</body>
</html>
I'm just guessing here, but Jetty is a little too helpful sometimes when your application emits http response codes other than 200s. My recommendation is that you add some logic to your web.xml to short circuit Jetty's helpfulness. The full technique that got my application out of a similar issue is documented on: How do I suppress Jetty 8's default ErrorHandler?
Good luck.

Resources