Spring Security結(jié)合MyBatis的用戶及角色簡(jiǎn)單校驗(yàn)

介紹

what is Spring Security.png

這是Spring Security官方文檔的一段介紹,大概是講Spring Security為基于Java開(kāi)發(fā)的應(yīng)用程序提供了全面的安全服務(wù)凄诞,建議我們結(jié)合Spring去使用,現(xiàn)在有很多身份驗(yàn)證都是通過(guò)第三方的诈胜,但是Spring Security提供了自己的一組身份驗(yàn)證特性。具體來(lái)說(shuō),Spring Security目前支持所有這些技術(shù)的身份驗(yàn)證集成幔烛;

運(yùn)行原理

security.png

大概畫(huà)了security的主要攔截器的流程圖荆忍。

代碼實(shí)現(xiàn)

  1. 添加依賴

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-test</artifactId>
      <scope>test</scope>
    </dependency>
    
  2. yml配置

    server:
      port: 80
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/securite?useUnicode=true&characterEncoding=utf8
        username: root
        password: 123
    mybatis:
      configuration:
        map-underscore-to-camel-case: true
    
  3. 數(shù)據(jù)庫(kù)


    user.png

    roles 表示角色格带,多個(gè)角色用“,”隔開(kāi)刹枉,前綴是ROLE_叽唱。

  4. 實(shí)體類

    @Data
    public class UserModel {
    
        private int id;
        private String name;
        private String password;
        private int age;
        private String address;
        private String roles;
    }
    
  5. mapper層

    @Mapper
    public interface UserMapper {
        @Select("select * from user where name = #{name}")
        UserModel getUserByName(String name);
    }
    
  6. service 層

    @Service
    public class UserService {
    
        @Autowired
       private UserMapper userMapper;
    
        public UserModel getUserByName(String name) {
            return userMapper.getUserByName(name);
        }
    }
    
  7. UserDetailsService具體實(shí)現(xiàn)(這里就是具體校驗(yàn)過(guò)程)

    @Service
    public class MyUserDetailsService implements UserDetailsService {
    
        @Autowired
        private UserService userService;
    
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
            UserModel userModel = userService.getUserByName(s);
            if (userModel == null) {
                throw new UsernameNotFoundException("用戶不存在");
            }
    
            return new User(userModel.getName(), userModel.getPassword(),
                    createAuthority(userModel.getRoles()));
    
        }
        //這里是將數(shù)據(jù)庫(kù)的角色分割,構(gòu)造GrantedAuthority
        private List<SimpleGrantedAuthority> createAuthority(String roles) {
            String[] roleArray = roles.split(",");
            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
            for (String role : roleArray) {
                authorityList.add(new SimpleGrantedAuthority(role));
            }
            return authorityList;
        }
    }
    
  8. 攔截規(guī)則設(shè)置

    @EnableWebSecurity
    @Configuration
    public class MyWebSecuriteConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private MyUserDetailsService myUserDetailsService;
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()//攔截
                    .antMatchers("/", "/home").permitAll()//允許/微宝、/home的訪問(wèn)
                    .antMatchers("/user/**").hasAnyRole("USER")//用戶USER角色的用戶訪問(wèn)有關(guān)/user下面的所有
                    .antMatchers("/admin/**").hasAnyRole("ADMIN")//同上
                    .anyRequest().authenticated()//其它所有訪問(wèn)都攔截
                    .and()
                    .formLogin()//添加登陸
                    .loginPage("/login").permitAll()//登陸頁(yè)面“/login"允許訪問(wèn)
                    .defaultSuccessUrl("/buy")//成功默認(rèn)跳轉(zhuǎn)/buy
                    .permitAll()
                    .and()
                    .logout().logoutUrl("/logout")
                    .logoutSuccessUrl("/login")
                    .permitAll();//同上
    
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(myUserDetailsService);//添加實(shí)現(xiàn)的UserDetailsService
        }
    }
    
  9. controller

    @Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("home");
            registry.addViewController("/home").setViewName("home");
            registry.addViewController("/login").setViewName("login");
            registry.addViewController("/buy").setViewName("buy");
        }
    }
    
  10. 頁(yè)面就不貼出來(lái)了,請(qǐng)看源碼

源碼

Demo源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末棺亭,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子蟋软,更是在濱河造成了極大的恐慌镶摘,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件岳守,死亡現(xiàn)場(chǎng)離奇詭異凄敢,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)湿痢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)涝缝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人罐氨,你說(shuō)我怎么就攤上這事≡及。” “怎么了恰矩?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)萎胰。 經(jīng)常有香客問(wèn)我技竟,道長(zhǎng)榔组,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮换可,結(jié)果婚禮上锦担,老公的妹妹穿的比我還像新娘。我一直安慰自己缚态,他們只是感情好浆熔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布老虫。 她就那樣靜靜地躺著祈匙,像睡著了一般夺欲。 火紅的嫁衣襯著肌膚如雪伞剑。 梳的紋絲不亂的頭發(fā)上黎泣,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音衡便,去河邊找鬼。 笑死呆抑,一個(gè)胖子當(dāng)著我的面吹牛鹊碍,可吹牛的內(nèi)容都是我干的侈咕。 我是一名探鬼主播楼眷,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼狰住,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼芦拿!你這毒婦竟也來(lái)了蔗崎?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體缤骨,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡燎斩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年荡碾,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了铐尚。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡箕昭,死狀恐怖泌霍,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情藤为,我是刑警寧澤,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布夺刑,位于F島的核電站缅疟,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏性誉。R本人自食惡果不足惜窿吩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望错览。 院中可真熱鬧纫雁,春花似錦、人聲如沸倾哺。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至忌愚,卻和暖如春曲管,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背硕糊。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工院水, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人简十。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓檬某,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親螟蝙。 傳聞我的和親對(duì)象是個(gè)殘疾皇子恢恼,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容