国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Vue+Jwt+SpringBoot+Ldap完成登錄認證的示例代碼

2019-11-19 13:48:40
字體:
來源:轉載
供稿:網友

本人野生程序員一名,了解了一些微服務架構、前后端分離、SPA的知識后就想試試做點什么東西。之前一直做后端,前端只是有基礎知識。之前學習過angularjs,但當時就是一臉懵逼(完全看不懂是啥)就放棄了。最近又學了Vue,這次感覺總算明白了一些,但其中也跳過很多坑(應該還會更多),在這里寫下來記錄一下吧。

說回主題,之前傳統登錄認證的方法基本是由服務器端提供一個登錄頁面,頁面中的一個form輸入username和password后POST給服務器,服務器將這些信息與DB或Ldap中的用戶信息對比,成功則將這個用戶信息記錄到session中。

這里我就跳了第一個大坑。傳統方式前后端不分離,后端負責頁面渲染,但是在前后分離的情況下,后端只負責通過暴露的RestApi提供數據,而頁面的渲染、路由都由前端完成。因為rest是無狀態的,因此也就不會有session記錄到服務器端。

之前一直使用SpringSecurity+Cas+Ldap來做SSO,但是使用Vue做前端后我怎都想不出用之前的方法做SSO(這個坑真的爬了好久才爬出來)。后來終于想明白了上面說的session的問題(我是這么認為的也可能不對,CAS也有RestApi,但是按官網配置沒成功,放棄了)。

第一個問題,該如何解決SSO的問題呢,要說到JWT。JWT是個規范,各種語言有各種語言的實現,可以去官網查到。我淺薄的理解是有一個認證服務(你自己寫的,Db、Ldap什么都可以)這個認證服務會通過用戶的提交信息判斷認證是否成功,如果成功則查詢出一些用戶的信息(用戶名、角色什么的),然后JWT把這些信息加密成為一個token,返回給客戶端瀏覽器,瀏覽器把這些信息存儲在localstorage中,以后每次訪問資源都會在header中攜帶這個信息,服務器收到請求后使用和加密時相同的key解密密文,如果解密成功則視為用戶已經認證過(當然你可以在加密時添加以一個過期時間)也就完成了SSO。使用解密出的角色信息你就可以判斷這個用戶是否有權限執行一些業務。這樣做完后感覺好像SpringSecurity、Cas在SPA應用中的SSO似乎沒什么作用了,目前我是這么認為的(當然可能不對)

第一個問題差不多解決了,來說第二個問題。之前因為有session的存在,在訪問受保護的資源時如果服務器端沒有當前用戶的session,則會強制跳轉到登錄頁。那在前后分離的情況下要如何實現這個需求。思路是這樣的:利用Vue-Router的全局路由鉤子,在訪問任何頁面時先判斷localStorage中是否存在JWT加密后的token并且token是否過期,如果存在且沒有過期則正常跳轉到請求的頁面,不存在或者過期則跳轉到登錄頁重新認證。

思路說完了,上代碼

1.首先你需要一個Ldap,我使用的是AD。這里我建立了一個叫minibox.com的域,并且添加了一個Employees的OU,其中有2個子OU,子OU中創建了2個用戶。

在Groups中新建一些組,把之前創建的用戶加入到組中,這樣用戶就擁有了角色。

2.搭建SpringBoot環境

2.1pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>minibox</groupId> <artifactId>an</artifactId> <version>0.0.1-SNAPSHOT</version>  <!-- Inherit defaults from Spring Boot -->  <parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.5.1.RELEASE</version>  </parent>  <!-- Add typical dependencies for a web application -->  <dependencies>    <!-- MVC -->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <!-- Spring boot test -->    <dependency>       <groupId>org.springframework.boot</groupId>       <artifactId>spring-boot-starter-test</artifactId>       <scope>test</scope>     </dependency>     <!-- spring-boot-starter-hateoas -->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-hateoas</artifactId>    </dependency>    <!-- 熱啟動 -->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-devtools</artifactId>      <optional>true</optional>    </dependency>    <!-- JWT -->    <dependency>      <groupId>io.jsonwebtoken</groupId>      <artifactId>jjwt</artifactId>      <version>0.7.0</version>    </dependency>    <!-- Spring Ldap -->    <dependency>      <groupId>org.springframework.ldap</groupId>      <artifactId>spring-ldap-core</artifactId>      <version>2.3.1.RELEASE</version>    </dependency>    <!-- fastjson -->    <dependency>      <groupId>com.alibaba</groupId>      <artifactId>fastjson</artifactId>      <version>1.2.24</version>    </dependency>  </dependencies>  <!-- Package as an executable jar -->  <build>    <plugins>      <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-maven-plugin</artifactId>      </plugin>      <!-- Hot swapping -->      <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-maven-plugin</artifactId>        <dependencies>          <dependency>            <groupId>org.springframework</groupId>            <artifactId>springloaded</artifactId>            <version>1.2.0.RELEASE</version>          </dependency>        </dependencies>      </plugin>    </plugins>  </build></project>

2.2應用配置文件

#Logging_configlogging.level.root=INFOlogging.level.org.springframework.web=WARNlogging.file=minibox.log#server_config#使用了SSL,并且在ldap配置中使用了ldaps,這里同時也需要把AD的證書導入到server.keystore中。具體的可以查看java的keytool工具server.port=8443server.ssl.key-store=classpath:server.keystoreserver.ssl.key-store-password=miniboxserver.ssl.key-password=minibox#jwt#jwt加解密時使用的keyjwt.key=minibox#ldap_config#ldap配置信息,注意這里的userDn一定要寫這種形式。referral設置為follow,說不清用途,似乎只有連接AD時才需要配置ldap.url=ldaps://192.168.227.128:636ldap.base=ou=Employees,dc=minibox,dc=comldap.userDn=cn=Administrator,cn=Users,dc=minibox,dc=comldap.userPwd=qqq111!!!!ldap.referral=followldap.domainName=@minibox.com

3.Spring主配置類

package an;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.ldap.core.LdapTemplate;import org.springframework.ldap.core.support.LdapContextSource;@SpringBootApplication//相當于@Configuration,@EnableAutoConfiguration,@ComponentScanpublic class Application {  /*  * SpringLdap配置。通過@Value注解讀取之前配置文件中的值  */  @Value("${ldap.url}")  private String ldapUrl;  @Value("${ldap.base}")  private String ldapBase;  @Value("${ldap.userDn}")  private String ldapUserDn;  @Value("${ldap.userPwd}")  private String ldapUserPwd;  @Value("${ldap.referral}")  private String ldapReferral;  /*  *SpringLdap的javaConfig注入方式  */  @Bean  public LdapTemplate ldapTemplate() {    return new LdapTemplate(contextSourceTarget());  }  @Bean  public LdapContextSource contextSourceTarget() {    LdapContextSource ldapContextSource = new LdapContextSource();    ldapContextSource.setUrl(ldapUrl);    ldapContextSource.setBase(ldapBase);    ldapContextSource.setUserDn(ldapUserDn);    ldapContextSource.setPassword(ldapUserPwd);    ldapContextSource.setReferral(ldapReferral);    return ldapContextSource;  }  public static void main(String[] args) throws Exception {    SpringApplication.run(Application.class, args);  }}

3.1提供認證服務的類

package an.auth;import javax.naming.directory.Attributes;import javax.naming.directory.DirContext;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.ldap.NamingException;import org.springframework.ldap.core.AttributesMapper;import org.springframework.ldap.core.LdapTemplate;import org.springframework.ldap.support.LdapUtils;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import static org.springframework.ldap.query.LdapQueryBuilder.query;import java.util.Date;import java.util.HashMap;import java.util.Map;import an.entity.Employee;import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;@RestController@RequestMapping("/auth")public class JwtAuth {  //jwt加密密匙  @Value("${jwt.key}")  private String jwtKey;  //域名后綴  @Value("${ldap.domainName}")  private String ldapDomainName;  //ldap模板  @Autowired  private LdapTemplate ldapTemplate;  /**   * 將域用戶屬性通過EmployeeAttributesMapper填充到Employee類中,返回一個填充信息的Employee實例   */  private class EmployeeAttributesMapper implements AttributesMapper<Employee> {    public Employee mapFromAttributes(Attributes attrs) throws NamingException, javax.naming.NamingException {      Employee employee = new Employee();      employee.setName((String) attrs.get("sAMAccountName").get());      employee.setDisplayName((String) attrs.get("displayName").get());      employee.setRole((String) attrs.get("memberOf").toString());      return employee;    }  }  /**   * @param username 用戶提交的名稱   * @param password 用戶提交的密碼   * @return 成功返回加密后的token信息,失敗返回錯誤HTTP狀態碼   */  @CrossOrigin//因為需要跨域訪問,所以要加這個注解  @RequestMapping(method = RequestMethod.POST)  public ResponseEntity<String> authByAd(      @RequestParam(value = "username") String username,      @RequestParam(value = "password") String password) {    //這里注意用戶名加域名后綴 userDn格式:anwx@minibox.com    String userDn = username + ldapDomainName;    //token過期時間 4小時    Date tokenExpired = new Date(new Date().getTime() + 60*60*4*1000);    DirContext ctx = null;    try {      //使用用戶名、密碼驗證域用戶      ctx = ldapTemplate.getContextSource().getContext(userDn, password);      //如果驗證成功根據sAMAccountName屬性查詢用戶名和用戶所屬的組      Employee employee = ldapTemplate                            .search(query().where("objectclass").is("person").and("sAMAccountName").is(username),              new EmployeeAttributesMapper())          .get(0);      //使用Jwt加密用戶名和用戶所屬組信息      String compactJws = Jwts.builder()          .setSubject(employee.getName())          .setAudience(employee.getRole())          .setExpiration(tokenExpired)          .signWith(SignatureAlgorithm.HS512, jwtKey).compact();      //登錄成功,返回客戶端token信息。這里只加密了用戶名和用戶角色,而displayName和tokenExpired沒有加密      Map<String, Object> userInfo = new HashMap<String, Object>();      userInfo.put("token", compactJws);      userInfo.put("displayName", employee.getDisplayName());      userInfo.put("tokenExpired", tokenExpired.getTime());      return new ResponseEntity<String>(JSON.toJSONString(userInfo , SerializerFeature.DisableCircularReferenceDetect) , HttpStatus.OK);    } catch (Exception e) {      //登錄失敗,返回失敗HTTP狀態碼      return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);    } finally {      //關閉ldap連接      LdapUtils.closeContext(ctx);    }  }}

4.前端Vue

4.1使用Vue-cli搭建項目,并使用vue-router和vue-resource,不了解的可以搜索下

4.2 main.js

// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import VueRouter from 'vue-router'import VueResource from 'vue-resource'import store from './store/store'import 'bootstrap/dist/css/bootstrap.css'import App from './App'import Login from './components/login'import Hello from './components/hello'Vue.use(VueRouter)Vue.use(VueResource)//Vue-resource默認以payload方式提交數據,這樣設置之后以formData方式提交Vue.http.options.emulateJSON = true;const routes = [ {  path: '/login',  component : Login },{  path: '/hello',  component: Hello }]const router = new VueRouter({ routes})//默認導航到登錄頁router.push('/login')/*全局路由鉤子訪問資源時需要驗證localStorage中是否存在token以及token是否過期驗證成功可以繼續跳轉失敗返回登錄頁重新登錄 */router.beforeEach((to, from, next) => { if(localStorage.token && new Date().getTime() < localStorage.tokenExpired){  next() } else{  next('/login') }})new Vue({ el: '#app', template: '<App/>', components: { App }, router, store})

4.3 App.vue

<template> <div id="app">  <router-view></router-view> </div></template><script> export default {  name: 'app', }</script><style scoped></style>

4.4 login.vue

<template>  <div class="login-box">    <div class="login-logo">      <b>Admin</b>LTE    </div>    <div class="login-box-body">      <div class="input-group form-group has-feedback">        <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>        <input v-model="username" type="text" class="form-control" placeholder="username">        <span class="input-group-addon">@minibox.com</span>      </div>      <div class="input-group form-group has-feedback">        <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>        <input v-model="password" type="password" class="form-control" placeholder="Password">      </div>      <div class="row">        <div class="col-sm-6 col-sm-offset-3 col-md-6 col-md-offset-3">          <transition name="slide-fade">            <p v-if="show">用戶名或密碼錯誤</p>          </transition>        </div>      </div>      <div class="row">        <div class="col-sm-6 col-sm-offset-3 col-md-6 col-md-offset-3">          <button v-on:click="auth" class="btn btn-primary btn-block btn-flat">Sign In</button>        </div>      </div>    </div>  </div></template><script>  //提供認證服務的restApi  var authUrl = 'https://192.168.227.1:8443/auth'  export default {    name: 'app',    data() {      return {        username: '',        password: '',        show: false      }    },    methods: {      auth: function(){        var credentials = {          username:this.username,          password:this.password        }        /*        post方法提交username和password        認證成功將返回的用戶信息寫入到localStorage,并跳轉到下一頁面        失敗提示認證錯誤        */        this.$http.post(authUrl, credentials).then(response => {          localStorage.token = response.data.token          localStorage.tokenExpired = response.data.tokenExpired          localStorage.userDisplayName = response.data.displayName          this.$router.push('hello')        }, response => {          this.show = true        })      }    }  }</script><style scoped>  p{    text-align: center  }  .slide-fade-enter-active {    transition: all .8s ease;  }  .slide-fade-leave-active {    transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);  }  .slide-fade-enter, .slide-fade-leave-to  /* .slide-fade-leave-active for <2.1.8 */ {    transform: translateX(10px);    opacity: 0;  }  @import '../assets/css/AdminLTE.min.css'</style>

5效果

5.1訪問http://localhost:8000時被導航到登錄頁

5.2提交登錄信息并取得token,跳轉下一頁

到這里整個功能就完成了。本人也是菜鳥一枚,理解有錯誤的地方還請各位老師指正。打算把整個分布式系統的開發過程記錄下來。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜兰县| 若尔盖县| 微博| 集安市| 怀仁县| 水城县| 康定县| 枣强县| 弥勒县| 永福县| 崇阳县| 临朐县| 邯郸县| 奉节县| 金山区| 怀来县| 宁远县| 曲阳县| 宁波市| 潞西市| 太谷县| 光山县| 台江县| 旬阳县| 额济纳旗| 津市市| 普定县| 洪雅县| 商洛市| 罗甸县| 大足县| 宜宾市| 彭泽县| 长沙市| 屏南县| 屯留县| 漳州市| 平罗县| 青田县| 浪卡子县| 崇明县|