Monday, April 8, 2019
On April 08, 2019 by Kamlesh 1 comment
Before diving into this implementation, I would suggest you to look at Spring Security Introduction first.
Let's Start
Most of the Web Applications uses custom login page with custom authentication,So lets go with it.
<html>
<body>
<form method="post" action="/login">
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
${logoutmsg}
UserName <input type="text" name="username"/>
<br/>
Password <input type="password" name="password"/>
<br/>
<input type="submit">
</form>
</body>
</html>
Login page is ready,Method should be post and action "/login" to invoke spring security,The EL tag ${sessionScope) will display recent exception message thrown by the springs.
Lets create a user entity now.
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.validator.constraints.NotBlank;
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@NotBlank
private String username;
@NotBlank
private String password;
@NotBlank
private String role;
}
When the username and password is submitted from login page,the security config file which extends WebSecurityConfigurerAdapter will be invoked.
Custom Authenticator is used in below example
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
CustomAuthentication customauthentication;
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customauthentication); //The Custom Authenticator is used here.
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//CSFR is disabled,if you dont know what csrf is,Spring has a beautiful documentaion about it ,Check it out.
http.csrf().disable();
//Login,logout page and resources are permitted for all users
http.authorizeRequests().antMatchers("/","/login","/logout","/resources/**").permitAll();
//userInfo page requires login as ROLE_USER or ROLE_ADMIN.
// If no login, it will redirect to /login page.
http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");
// For ADMIN only.
http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");
//Login and logout configurations
//username and password parameter must match the login form username and password parameter
//When the user logs out,it will be redirected to login page as specified,it is always good practice to display a logout message whwn the user logs
out,To display a logout message,follow the last snippet.
//On Successful login user will be redirected to "/index" page as specified below else back to login page.
http.authorizeRequests().and().
formLogin().loginProcessingUrl("/login").loginPage("/login").defaultSuccessUrl("/index")
.failureUrl("/login?error=true").usernameParameter("username").passwordParameter("password").
and().
logout().logoutSuccessUrl("/login?logout");
// If no login, it will redirect to /login page.
http.authorizeRequests().antMatchers("/**").authenticated();
//Handling Access Denied Request
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/accessdenied");
}
}
Simple Custom Authentication would look like below one,logic might change based on your requirements.
public class CustomAuthentication implements AuthenticationProvider {
@Autowired
private UserRepository userrepository;
@Override
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String username = auth.getName();
String password = auth.getCredentials().toString();
User user = userrepository.findByUsername(username);
if(user==null){
throw new BadCredentialsException("Username Not Found");
}
if(!password.equals(user.getPassword)){
throw new BadCredentialsException("Username Or Password Is invalid");
}
return new UsernamePasswordAuthenticationToken(username,password,
Arrays.asList(new SimpleGrantedAuthority(user.getRole())));
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
In the above code exception is thrown with a relevant message if the condition fails,these messages are displayed on login page by EL tag ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}.
If everything checks out,user will be forwarded to welcome page as specified in the security config file.
On Successfully logging out , /login is called which hits the controller,You can set the logout message there as shown below
@RequestMapping(value="/login")
public String showLogin(String error,String logout,Model model) {
if(logout!=null)
model.addAttribute("logoutmsg", "You've been logged out Successfully");
return "login";
}
Let's Start
Most of the Web Applications uses custom login page with custom authentication,So lets go with it.
<html>
<body>
<form method="post" action="/login">
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
${logoutmsg}
UserName <input type="text" name="username"/>
<br/>
Password <input type="password" name="password"/>
<br/>
<input type="submit">
</form>
</body>
</html>
Login page is ready,Method should be post and action "/login" to invoke spring security,The EL tag ${sessionScope) will display recent exception message thrown by the springs.
Lets create a user entity now.
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.validator.constraints.NotBlank;
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@NotBlank
private String username;
@NotBlank
private String password;
@NotBlank
private String role;
}
When the username and password is submitted from login page,the security config file which extends WebSecurityConfigurerAdapter will be invoked.
Custom Authenticator is used in below example
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
CustomAuthentication customauthentication;
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customauthentication); //The Custom Authenticator is used here.
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//CSFR is disabled,if you dont know what csrf is,Spring has a beautiful documentaion about it ,Check it out.
http.csrf().disable();
//Login,logout page and resources are permitted for all users
http.authorizeRequests().antMatchers("/","/login","/logout","/resources/**").permitAll();
//userInfo page requires login as ROLE_USER or ROLE_ADMIN.
// If no login, it will redirect to /login page.
http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");
// For ADMIN only.
http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");
//Login and logout configurations
//username and password parameter must match the login form username and password parameter
//When the user logs out,it will be redirected to login page as specified,it is always good practice to display a logout message whwn the user logs
out,To display a logout message,follow the last snippet.
//On Successful login user will be redirected to "/index" page as specified below else back to login page.
http.authorizeRequests().and().
formLogin().loginProcessingUrl("/login").loginPage("/login").defaultSuccessUrl("/index")
.failureUrl("/login?error=true").usernameParameter("username").passwordParameter("password").
and().
logout().logoutSuccessUrl("/login?logout");
// If no login, it will redirect to /login page.
http.authorizeRequests().antMatchers("/**").authenticated();
//Handling Access Denied Request
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/accessdenied");
}
}
Simple Custom Authentication would look like below one,logic might change based on your requirements.
public class CustomAuthentication implements AuthenticationProvider {
@Autowired
private UserRepository userrepository;
@Override
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String username = auth.getName();
String password = auth.getCredentials().toString();
User user = userrepository.findByUsername(username);
if(user==null){
throw new BadCredentialsException("Username Not Found");
}
if(!password.equals(user.getPassword)){
throw new BadCredentialsException("Username Or Password Is invalid");
}
return new UsernamePasswordAuthenticationToken(username,password,
Arrays.asList(new SimpleGrantedAuthority(user.getRole())));
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
In the above code exception is thrown with a relevant message if the condition fails,these messages are displayed on login page by EL tag ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}.
If everything checks out,user will be forwarded to welcome page as specified in the security config file.
On Successfully logging out , /login is called which hits the controller,You can set the logout message there as shown below
@RequestMapping(value="/login")
public String showLogin(String error,String logout,Model model) {
if(logout!=null)
model.addAttribute("logoutmsg", "You've been logged out Successfully");
return "login";
}
Subscribe to:
Post Comments (Atom)
Search
AdSense
Recent Posts
Popular Posts
-
WLST Script for checking the health status of Weblogic Domain (Admin/Managed node) After long time writing something about WLST WLST...
-
WLST Script for checking the status of JDBC Datasource in Weblogic WLST has some good features like we can monitor the weblogic dom...
-
WLST Script for Monitoring the JMS status of Weblogic Domain After long time writing something about WLST WLST has some good feature...
-
WLST Server Start The server of a WebLogic domain can be started using different techniques. The best setup depends on the technical re...
-
How to Deploy Application using WLST We can use WLST to quickly deploy an Application in a Weblogic Server. Requirement:- · The ...
-
How to create WebLogic Domain using Domain template: 1. Open an existing domain template (assuming WebLogic Server is installed at c:...
-
Basic concepts of WLST. What is WLST? It is a scripting tool offered by Weblogic. Any way WLST is not only for a sense of control,...
-
Hi All, writing something about OPMN utility with oracle instance and Weblogic. WebLogic Server – Weblogic is J2EE application ...
-
Hadoop Distributed Filesystem (HDFS) Built to support high throughput, streaming reads and writes of extremely large files. NAS ...
-
Before diving into this implementation, I would suggest you to look at Spring Security Introduction first. Let's Start Most of the We...
Recent Posts
Sample Text
Blog Archive
-
▼
2019
(13)
-
▼
April
(13)
- Spring MVC vs Spring Boot
- Spring Security With Spring Boot Example
- What is Spring Security?
- Adding your own implementation in JPA
- Crud Operations using Spring Data JPA
- What is Spring Boot JPA?
- YAML and Application.Properties Configuration in S...
- How Controller works in Spring Boot?
- What is Annotation?
- Setting up Spring Boot
- Why Spring Boot?
- What is Spring Boot?
- Spring Boot Tutorials
-
▼
April
(13)
Total Pageviews
Find Us On Facebook
Powered by Blogger.
In this manner my buddy Wesley Virgin's report starts in this shocking and controversial VIDEO.
ReplyDeleteAs a matter of fact, Wesley was in the army-and shortly after leaving-he discovered hidden, "MIND CONTROL" tactics that the CIA and others used to get whatever they want.
As it turns out, these are the exact same SECRETS tons of famous people (especially those who "became famous out of nowhere") and top business people used to become wealthy and successful.
You probably know that you utilize only 10% of your brain.
Really, that's because most of your BRAINPOWER is UNCONSCIOUS.
Maybe this thought has even taken place IN YOUR very own brain... as it did in my good friend Wesley Virgin's brain 7 years back, while riding an unlicensed, beat-up trash bucket of a vehicle with a suspended driver's license and on his debit card.
"I'm so fed up with going through life paycheck to paycheck! When will I get my big break?"
You've taken part in those conversations, isn't it so?
Your success story is going to be written. You just have to take a leap of faith in YOURSELF.
WATCH WESLEY SPEAK NOW