How to connect html file in resources folder with Spring Boot? - java

My SpringWebConfiguration.class is here:
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private static Logger logger = LoggerFactory.getLogger(SpringSecurityConfig.class);
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
logger.info("-----configure(HttpSecurity http)");
http.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.loginPage("/login")//
.defaultSuccessUrl("/userAccountInfo")//
.failureUrl("/login?error=true")//
.usernameParameter("username")//
.passwordParameter("password")
.defaultSuccessUrl("/")
.permitAll().
and().rememberMe().rememberMeParameter("remember-me").key("uniqueAndSecret").tokenValiditySeconds(1296000).userDetailsService(userDetailsService)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
.deleteCookies("guid")
.deleteCookies("JSESSIONID")
.permitAll()
.and().csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
logger.info("-----configureGlobal(AuthenticationManagerBuilder auth)");
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
}
My LoginController:
#RestController
public class LoginController() {
#GetMapping("/login")
public String login(Model model) {
return "/login";
}
}
My html file:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Stacked form</h2>
<form th:action="#{/login}" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="remember"> Remember me
</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
When I open browser and go to "localhost:8080/login". It returns String "/login", not html login page. Why? Maybe I missed something to connect to my html file. I think my controller need something like an url to connect to html file. I don't understand how it work correctly. Help me please!

First, you need to modify LoginController
#Controller
public class LoginController() {
#GetMapping("/login")
public String login(Model model) {
return "/login";
}
}
If it does not work then convert html to jsp page.

#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Add ViewResolver to your configuration class along with your code.

You need to add a view resolver to your spring configurations.
This ViewResolver allows us to set properties such as prefix or suffix to the view name to generate the final view page URL
Example:
#EnableWebMvc
#Configuration
#ComponentScan("com.baeldung.web")
public class WebConfig implements WebMvcConfigurer {
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
For such simplicity of the example, we don't need a controller to process the request.
We only need a simple jsp page, placed in the /WEB-INF/view folder as defined in the configuration.
Source:
https://www.baeldung.com/spring-mvc-view-resolver-tutorial

Related

i always get error 403 when use custom login form spring security

there is always 403 error when i log in even with correct username and password
html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<link rel="stylesheet" th:href="#{/css/stylesheet.css}"/>
<title>Spring Security Example </title>
</head>
<body>
<header th:insert="navbar :: header"></header>
<form th:action="#{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
configuration:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/css/**").authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/")
.defaultSuccessUrl("/")
.permitAll();
}
#Bean
#Override
protected UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
User.builder()
.username("admin")
.password(passwordEncoder().encode("admin"))
.roles("ADMIN")
.build()
);
}
#Bean
protected PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
controller:
#Controller
public class WebController {
#Autowired
private UserRepository userRepository;
#GetMapping("/")
public String getHome(Model model) {
return "home";
}
#GetMapping("/registration")
public String getRegistration(Model model) {
return "registration";
}
#GetMapping("/add")
public String getAddPicture(Model model) {
return "addPicture";
}
#GetMapping("/login")
public String getLogin(Model model) {
return "login";
}
#GetMapping("/pictures")
public String getPicture(Model model) {
return "pictures";
}
#PostMapping("/registration")
public String addNewUser (#RequestParam String password, #RequestParam String email, #RequestParam String username) {
User user = new User(password, email, username, true);
userRepository.save(user);
return "home";
}
}
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error type=Forbidden, status=403
Forbidden blablalblalallbmrtfg It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.

Spring Security: Page does not redirect after login

I've built a webapp from scratch using Spring boot and Java. Now I want to integrate Spring Security into the system.
However, I'm having problem with logging in using Spring Security. I used a customize login page and I had configured it correctly. Not sure what am I missing.
Main
#SpringBootApplication
#ComponentScan(basePackages = {"com.security"}, basePackageClasses = {LoginController.class})
#EntityScan(basePackages = {"com.auth"})
#EnableJpaRepositories(basePackages = {"com.auth.repository"})
public class CpexProjectApplication {
public static void main(String[] args) {
SpringApplication.run(CpexProjectApplication.class, args);
}
}
Controller
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String getLogin() {
return "login";
}
}
Security Config
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
#EnableJpaRepositories(basePackageClasses = UserRepository.class)
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomUserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(getPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/css/**","/scss/**","/vendor/**","/img/**","/js/**").permitAll()
.antMatchers(HttpMethod.POST, "/home/**").hasRole("ADMIN")
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home/**")
.permitAll();
}
private PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
#Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
#Override
public boolean matches(CharSequence charSequence, String s) {
return true;
}
};
}
}
Custom class of UserDetails
#SuppressWarnings("serial")
public class CustomUserDetails extends User implements UserDetails {
public CustomUserDetails(final User user) {
super(user);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
.collect(Collectors.toList());
}
#Override
public String getPassword() {
return super.getPassword();
}
#Override
public String getUsername() {
return super.getName();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
application.properties
#CPEX database - UAT
spring.datasource.url=jdbc:sqlserver://10.100.2.254;databaseName=ROOT
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto=update
#View Resolver
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
#Bean Override
spring.main.allow-bean-definition-overriding=true
#For detailed logging during dev
logging.level.org.springframework=DEBUG
#Tomcat default port
server.port=8888
login page
<!DOCTYPE html>
<html lang="en">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>CPEX - Login</title>
<!-- Custom fonts for this template-->
<link type="text/css" href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<!-- Custom styles for this template-->
<link href="css/sb-admin-2.min.css" rel="stylesheet">
</head>
<body class="bg-gradient-primary">
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-xl-10 col-lg-12 col-md-9">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-6 d-none d-lg-block bg-login-image border-right border-3">
<img class="img-responsive" src="img/sbc-logo.png" alt="">
<div id="loginSuccessAlert" class="alert alert-success" style="display: none;">
<strong>Login Successful!</strong>
</div>
<div id="loginDangerAlert" class="alert alert-danger" style="display: none;">
<strong>Please check your credentials.</strong>
</div>
</div>
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4 display-4">CP Exchange</h1>
</div>
<form id="loginForm" class="user" action="home" method="POST">
<div class="form-group">
<input type="text" class="form-control form-control-user" id="name" name="name" placeholder="Enter Username...">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-user" id="password" name="password" placeholder="Password">
</div>
<input class="btn btn-primary btn-user btn-block" type="submit" value="Login" />
<hr>
</form>
<div class="text-center">
<a class="small" href="#">Forgot Password?</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin-2.min.js"></script>
<!-- <script src="js/custom/validateLogin.js"></script> -->
</body>
</html>
home page
code is too long
CustomUserDetailsService
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
Optional<User> optionalUsers = userRepository.findByName(name);
optionalUsers
.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
return optionalUsers
.map(CustomUserDetails::new).get();
}
}
TIA
Just noticed your Login JSP Submit will trigger /home which you have configured as defaultSuccessUrl and it will return Login page as you are not yet logged in.
Please change below line in your login.jsp
<form id="loginForm" class="user" action="home" method="POST">
to
<form id="loginForm" class="user" action="perform_login" method="POST">
Also you can remove this line
.antMatchers(HttpMethod.POST, "/home/**").hasRole("ADMIN")
and add
.loginProcessingUrl("/perform_login")
from configure method for now just to try.
If it works go ahead and add other configuration one by one.
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/css/**","/scss/**","/vendor/**","/img/**","/js/**").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/perform_login") // add Login submit url
.defaultSuccessUrl("/home/**")
.permitAll();
EDIT 1:
If you are using inMemoryAuthentication add userDetailsService as well like this
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(getPasswordEncoder())
.withUser("admin").password("aaa11111").roles("ADMIN").and()
.withUser("user").password("bbb22222").roles("USER");
auth.userDetailsService(userDetailsService);
}

Login Error in SpringBoot 2.1.4.RELEASE WebApp

I have a basic SpringBoot 2.1.4.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file. with those methods in the security config file:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserSecurityService userSecurityService;
/** The encryption SALT. */
private static final String SALT = "asd31*(_)nof";
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(publicMatchers()).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/calzadas/list")
.failureUrl("/login?error").permitAll()
.and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.eraseCredentials(false)
.userDetailsService(userSecurityService)
.passwordEncoder(passwordEncoder());
}
private String[] publicMatchers() {
/** Public URLs. */
final String[] PUBLIC_MATCHERS = {
"/webjars/**",
serverContextPath + "/css/**",
serverContextPath + "/js/**",
serverContextPath + "/fonts/**",
serverContextPath + "/images/**",
serverContextPath ,
"/",
"/error/**/*",
"/console/**",
SignupController.USER_VALIDATION_URL_MAPPING
};
return PUBLIC_MATCHERS;
}
}
and
#Service
public class UserSecurityService implements UserDetailsService {
/** The application logger */
private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
LOG.info("Searching user with email: " + email);
User user = userRepository.findByEmailIgnoreCase(email);
LOG.info("user: {} " + user);
if (null == user) {
LOG.warn("Username {} not found", email);
throw new UsernameNotFoundException("Username " + email + " not found");
}
return user;
}
}
on the login.html:
<div th:if="${param.error}" class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<p th:text="#{login.error.message}" />
</div>
on the other hand I have a RestController also for the validation:
#RestController
public class AuthenticationRestController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Autowired
private UserSecurityService userSecurityService;
#Autowired
private EmailService emailService;
...
/**
* Authenticates the user. If something is wrong, an {#link AuthenticationException} will be thrown
*/
private void authenticate(String username, String password) {
Objects.requireNonNull(username);
Objects.requireNonNull(password);
if (StringUtils.isEmpty(username)) throw new AuthenticationException();
if (StringUtils.isEmpty(password)) throw new AuthenticationException();
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new AuthenticationException("User is disabled!", e);
} catch (BadCredentialsException e) {
throw new AuthenticationException("Bad credentials!", e);
}
}
}
I don't know why with the Web authentication I can't log, I got always an error, Bad credential ? , but with the RestController I can log using the same credentials, and I don't know how to figure out what is the difference ...
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="pradera/common/header :: common-header" />
<link rel="stylesheet" th:href="#{/pradera/css/login.css}" type='text/css' />
<!-- for the error login message box -->
<link th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" rel="stylesheet" media="screen" />
<body>
<div class="wrap">
<div class="login">
<div class="logo"><img th:src="#{pradera/images/login.png}" width="224" height="71" alt="pradera Cloud" /></div>
<form id="loginForm" th:action="#{/login}" method="post">
<div class="row">
<div class="col-md-6 col-md-offset-3 text-center">
<div th:if="${param.error}" class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<p th:text="#{login.error.message}" />
</div>
<div th:if="${param.logout}" class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<p th:text="#${param.error}" />
</div>
</div>
</div>
<div class="input_label"><i class="fa fa-user"></i><input type="text" id="usernameId" name="username" th:attr="placeholder=#{login.user.placeholder}" value="ricard.olle#gmail.com" /></div>
<div class="input_label"><i class="fa fa-key"></i><input type="password" name="password" placeholder="Password" value="Iconofcoil100#"/></div>
<input type="submit" value="LOGIN" />
</form>
<div class="forget">
<a th:href="#{/signup?planId=1}" th:text="#{login.register.text}">Register</a><br/>
<br/>
</div>
<div class="forget">
<a th:href="#{/forgotmypassword}" th:text="#{login.forgot.password.text}" >Do you forgot your password</a><br/>
<br/>
<br/>
<br/>
<br/>
<span>Powered By Cryptsonic.io 2018 ©</span>
</div>
</div>
</div>
<!-- Js zone -->
<div th:replace="pradera/common/header :: before-body-scripts" ></div>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
<script type="text/javascript">
$( document ).ready(function() {
$( "#usernameId" ).focus();
});
$(document).keypress(function(e) {
if(e.which == 13) {
$( "#loginForm" ).submit();
}
});
</script>
</body>
</html>
and
#Repository
public interface UserRepository extends CrudRepository<User, Long> {
/**
* Returns a User given a username or null if not found.
* #param username The username
* #return a User given a username or null if not found.
*/
User findByUsernameIgnoreCase(String username);
/**
* Returns a User for the given email or null if none was found.
* #param email The user's email
* #return a User for the given email or null if none was found.
*/
User findByEmailIgnoreCase(String email);
..
}
and I see in the logs that the user is retrieved:
2019-04-21 10:56 [http-nio-2233-exec-3] INFO i.i.b.service.UserSecurityService.loadUserByUsername(39) - user: {} com.bonanza.backend.persistence.domain.backend.User#5a3163ef
Try activating the debug logging for Spring security:
<logger name="org.springframework.security" level="debug" />

spring security with spring boot cant redirect after login

I encountered a problem when integrating spring security with spring boot.After Overwriting the WebSecurityConfigurerAdapter, I can't redirect to the successful page(wlecome.ftl) when I've accessed the login page.It's aways redirect to the login page(index.ftl) without error logs.
Is there anyting I missed?Help is aways appreciated,thanks!
SecurityConfig.java
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
MyUserDetailsService detailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user/**").hasRole("USER")
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/user/welcome")//add this but not work
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico");
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
}
Login.Controller
#Controller
public class LoginController {
#RequestMapping("/login")
public String login(){
return "index";
}
#RequestMapping("/user/welcome")
public String welcome(){
return "user/welcome";
}
index.ftl(the login page)
<!DOCTYPE html>
<#import "/spring.ftl" as spring />
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="<#spring.url '/login' />" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
welcome.ftl
<html>
<head>
</head>
<body>
welcome
</body>
</html>
You didn't set the successful login url and you anywhere redirect after login success. Put the:
defaultSuccessUrl("/user/welcome")
after the:
passwordParameter("...")
in your security configuration.
try this
.defaultSuccessUrl("/user/welcome",true)

How to separate content for unregistred and registred users

The problem is:
The site has one content for people who have not yet registered and another for those who have already registered and logged in. When I enter the site, I am thrown onto the page /login as I have indicated in Spring Security and this page does not allow me to go anywhere until I log in. But I need to throw me at the entrance to the site to the home page for unregistered users where i can view information about the event, and etc, and then register or log in. I almost decided that, I added to the Spring Security class .loginPage("/index") instead of ("/login") + added antMatchers, where he indicated all the pages that an unregistered user can visit. But there was a problem. It is shown in the picture. My styles do not work, it also stops showing pictures.
I add to antMatchers "/resources/**" but this does not help. Also, when I go to the "log in" tab from the main page, and I try to log in by entering my login and password, write an error
"Request method 'POST' not supported
org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'POST' not supported at "
My Sping Secutiry code before update -
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Qualifier("userDetailsServiceImpl")
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private SimpleAuthenticationSuccessHandler successHandler;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/runner/**").hasAnyRole("RUNNER","ADMIN")
.antMatchers("/coordinator/**").hasAnyRole("COORDINATOR","ADMIN")
.anyRequest().authenticated().and()
.formLogin()
.loginPage("/login")
.successHandler(successHandler)
.permitAll().and()
.logout()
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers( "/static/**", "/css/**", "/js/**","/error");
}
}
My Sping Secutiry code after update - the rest is the same
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/runner/**").hasAnyRole("RUNNER","ADMIN")
.antMatchers("/coordinator/**").hasAnyRole("COORDINATOR","ADMIN")
.antMatchers( "/aboutEvent","/marathonCompare","/charityOrgList",
"/calculatorBMI","/calculatorBMR","/learnMore","/registerAsRunner","/becomeSponsor","/",
"/allResults","/interactiveMap","/becomeRunner","/login","/resources/**").permitAll()
.anyRequest().authenticated().and()
.formLogin()
.loginPage("/index")
.successHandler(successHandler)
.permitAll().and()
.logout()
.permitAll();
}
Login Controller
#Controller
public class LoginController {
#GetMapping("/login")
public String login(){
return "login/login";
}
}
Login Page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous" th:href="#{/webjars/bootstrap/4.1.3/css/bootstrap.min.css}">
<link rel="stylesheet" type="text/css" media="all" th:href="#{/css/runnerstyle/register.css}"/>
</head>
<body class="align">
<div class="register-top flex-container">
<form th:action="#{/index}">
<button type="submit" class="register-back">Назад</button>
</form>
<h1><b>MARATHON SKILLS 2018</b></h1>
</div>
<div class="login-middle">
<div class="login-text">
<h2>Форма авторизации<br/></h2>
<h4>Пожалуйста, авторизуйтесь в системе, используя ваш адресс электронной почты<br>
и пароль.
</h4>
</div>
<div th:if="${param.error}" class="alert alert-danger">
<p>Invalid username or password</p>
</div>
<div th:if="${param.logout}" class="alert alert-success">
<p>You've been logged out</p>
</div>
<form th:action="#{/login}" method="post" class="form-input">
<table>
<tr th:class="${param.error} ? 'form-group has-error' : 'form-group'">
<th><h4>Email:</h4></th>
<th style="padding-left: 20px">
<input type="email" id="username" name="username" placeholder="Enter your email address" size="60px" class="input-field">
</th>
</tr>
<tr th:class="${param.error} ? 'form-group has-error' : 'form-group'">
<th><h4>Password:</h4></th>
<th style="padding-left: 20px">
<input type="password" id="password" name="password" placeholder="Enter your email password" size="60px" class="input-field">
</th>
</tr>
<tr>
<th></th>
<th style="padding-right: 13vw;">
<button type="submit" class="login-button">Login</button>
Cancel
</th>
</tr>
</table>
</form>
</div>
<div class="register-bot">
18 дней 8 часов и 17 минут осталось до старта марофона!
</div>
</body>
</html>
Index controller
#Controller
public class IndexController {
#GetMapping({"/","/index",""})
public String getIndexPage(){
return "index";
}
#GetMapping("/registerAsRunner")
public String registerRunner(){
return "runner/createOrRegister";
}
#GetMapping("/learnMore")
public String getLearnMorePage(){return "learnmore/main";}
}
How can I solve this problem and do what I have in mind? Thanks!

Categories

Resources