spring security登陆认证demo

来源:互联网 发布:mac装软件用什么程序 编辑:程序博客网 时间:2024/05/17 21:06

demo classes

package com.nroad.model;import javax.persistence.*;/** * Created by jiyy on 2017/1/8. */@Entity@Table(name = "user", schema = "test")public class User {    @Id    @GeneratedValue(strategy = GenerationType.AUTO)    @Column(name = "id", unique = true, nullable = false)    private long id;    @Column(name = "name", unique = true, nullable = false)    private String name;    @Column(name = "password",nullable = false)    private String  password;    @Column(name="role")    @Enumerated(EnumType.STRING)    private Role role;    public User() {    }    public User(String name) {        this.name = name;    }    public User(long id, String name, String password, Role role) {        this.id = id;        this.name = name;        this.password = password;        this.role = role;    }    public long getId() {        return id;    }    public void setId(long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public Role getRole() {        return role;    }    public void setRole(Role role) {        this.role = role;    }   /* @Override    public int hashCode() {        return super.hashCode();    }    @Override    public boolean equals(Object obj) {        return super.equals(obj);    }    @Override    public String toString() {        return super.toString();    }*/}
package com.nroad.model;/** * Created by jiyy on 2017/1/8. */public enum Role {    ADMIN,    ORDINARY}
package com.nroad.security;import com.nroad.dao.UserDao;import com.nroad.model.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;import java.util.ArrayList;import java.util.List;/** * Created by jiyy on 2017/1/8. */@Service("customUserDetailsService")public class CustomUserDetailsService implements UserDetailsService {    @Autowired    UserDao userDao;    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        User user = userDao.findByName(username);        if(user == null){            throw new UsernameNotFoundException("not found");        }        List<SimpleGrantedAuthority> authorities = new ArrayList<>();        authorities.add(new SimpleGrantedAuthority(user.getRole().name()));        System.err.println("username is " + username + ", " + user.getRole().name());        return new org.springframework.security.core.userdetails.User(user.getName(),                user.getPassword(), authorities);    }}
package com.nroad.security;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.UserDetailsService;/** * Created by jiyy on 2017/1/6. */@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter{    @Override    @Bean    public UserDetailsService userDetailsService() {        return new CustomUserDetailsService();    }    @Override    protected void configure(AuthenticationManagerBuilder auth)            throws Exception {        auth.userDetailsService(userDetailsService());    }    @Override    protected void configure(HttpSecurity http) throws Exception {        http                .authorizeRequests()                    .antMatchers("/", "/home").permitAll()                    .anyRequest().authenticated()                    .and()                .formLogin()                    .loginPage("/login")                    .defaultSuccessUrl("/helloAdmin")                    .permitAll()                    .and()                .logout()                    .permitAll();    }    /*@Autowired    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {        auth                .inMemoryAuthentication()                .withUser("user").password("password").roles("USER");    }*/}
package com.nroad.security;import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;import org.springframework.boot.web.servlet.ErrorPage;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpStatus;/** * Created by jiyy on 2017/1/8. */@Configurationpublic class ErrorPageConfig {    @Bean    public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){        return new MyCustomizer();    }    private static class MyCustomizer implements EmbeddedServletContainerCustomizer {        @Override        public void customize(ConfigurableEmbeddedServletContainer container) {            container.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/403"));        }    }}
package com.nroad.service;import com.nroad.dao.UserDao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;/** * Created by jiyy on 2017/1/8. */@Servicepublic class DataInit {    @Autowired    UserDao userDao;    @PostConstruct    public void dataInit(){        /*User admin = new User();        admin.setPassword("admin");        admin.setName("admin");        admin.setRole(Role.ADMIN);        userDao.save(admin);        User user = new User();        user.setPassword("user");        user.setName("user");        user.setRole(Role.ORDINARY);        userDao.save(user);*/    }}
package com.nroad.controller;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;/** * Created by jiyy on 2017/1/5. */@Controller//@SpringBootApplicationpublic class DemoController {    @RequestMapping(value = "/helloAdmin", method=RequestMethod.GET)    @PreAuthorize("hasAnyRole('ADMIN')")    public String helloAdmin(){        return "helloAdmin";    }    @RequestMapping(value = "/helloUser", method=RequestMethod.GET)    @PreAuthorize("hasAnyRole('ADMIN', 'ORDINARY')")    public String helloUser(){        return "helloUser";    }}
package com.nroad.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;/** * Created by jiyy on 2017/1/5. */@Controllerpublic class LoginController {    @RequestMapping(value = {"/", "/home"})    public String index(){        return "index";    }    @RequestMapping(value = "/login"/*,method = RequestMethod.POST*/)    public String login() {        return "login";    }    @RequestMapping(value = "/doLogin",method = RequestMethod.POST)    public String doLogin(@RequestParam(value = "name", required = false) String name,                          @RequestParam(value = "password", required = false) String password){        System.out.print(name);        System.out.print(password);        return "hello";    }    @RequestMapping("/403")    public String forbidden(){        return "403";    }}
package com.nroad.controller;import org.springframework.stereotype.Controller;/** * Created by jiyy on 2017/1/8. */@Controllerpublic class HomeController {/*    @RequestMapping(value = {"", "/home"}, method= RequestMethod.GET)    public String home(){        return "/hello/home";    }    @RequestMapping(value = "/helloadmin", method=RequestMethod.GET)    @PreAuthorize("hasAnyRole('ADMIN')")    public String helloAdmin(){        return "/hello/helloAdmin";    }    @RequestMapping(value = "/hellouser", method=RequestMethod.GET)    @PreAuthorize("hasAnyRole('ADMIN', 'ORDINARY')")    public String helloUser(){        return "/hello/helloUser";    }    @RequestMapping(value = "/login", method=RequestMethod.GET)    public String login(){        return "/hello/login";    }    @RequestMapping("/403")    public String forbidden(){        return "403";    }*/}

index.html

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head>    <meta charset="UTF-8"/>    <title>Spring Security入门</title></head><body><h1>欢迎使用Spring Security!</h1><p>点击 <a th:href="@{/login}">这里</a> 打个招呼吧</p></body></html>

login.html

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head>    <title>Spring Security Example </title></head><body><div th:if="${param.error}">    Invalid username and password.</div><div th:if="${param.logout}">    You have been logged out.</div><form th:action="@{/doLogin}" method="post">    <div><label> User Name : <input type="text" name="name"  th:value="${name}" /> </label></div>    <div><label> Password: <input type="password" name="password" th:value="${password}" /> </label></div>    <div><input type="submit" value="Sign In"/></div></form></body></html>

hello.html

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head>    <title>Hello World!</title></head><body><h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1><form th:action="@{/logout}" method="post">    <input type="submit" value="Sign Out"/></form></body></html>

helloAdmin.html

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head>    <title>Hello World!</title></head><body><h1>home admin page</h1></body></html>

helloUser.html

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head>    <title>Hello World!</title></head><body><h1>home user page</h1></body></html>
0 0