springboot+vue+keyclock

前提条件:keyclock上先配置好需要的信息

 

 

1 springboot接入keyclock

 先添加依赖

 

 <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
        </dependency>

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.keycloak.bom</groupId>
                <artifactId>keycloak-adapter-bom</artifactId>
                <version>5.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>

    </dependencyManagement>

 

配置文件

keycloak.auth-server-url = https://auth.souche-inc.com/auth
keycloak.realm = lantu
keycloak.resource = lantu-app
keycloak.security-constraints[0].authRoles[0] = ops  //指定角色  在keyclock上配置账号拥有的角色
keycloak.security-constraints[0].securityCollections[0].patterns[0] = /lantu/salt/*     //指定拦截路径
keycloak.credentials.secret = c82fb31d-c081-4605-9e66-9735b5ce1863             //去keyclock上找

这样后端拦截就做好了  

 

2 vue 配置

在路由界面配置此代码(根据个人情况修改变动):目的在每次访问后端前 验证一下是否能访问后端 若是不能则跳转登陆

//访问后端接口  
axios.get('https://lantu.souche-inc.com/lantu/salt/login',{
       }).then(respose=>{
// 访问成功则放行 
           next();
        }).catch(error=>{
//访问不成功  则跳转keyclock登陆
          let keycloak = null;
          keycloak = Keycloak({
            url: 'https://auth.souche-inc.com/auth/realms/lantu/protocol/openid-connect/auth?response_type=code&client_id=lantu-app&redirect_uri=https%3A%2F%2Flantu.souche-inc.com%2Flantu%2Fsalt%2Flogin&state=eb81218a-5718-494b-95a5-3b6b04ff23ac&login=true&scope=openid'   ,
            realm: 'lantu',
            clientId: 'lantu-app',
          });

          keycloak.init({onLoad: 'login-required'}).success(
            function (authenticated) {
           
              if (!authenticated) {
                alert('not authenticated')
              } else {

                keycloak.loadUserProfile().success(data => {
                  console.info(data)
                })
              }
              console.info(keycloak)
            }).error(function () {
            alert('failed to initialize');
          });
         })

 

posted @ 2019-04-19 15:50  口水青春  阅读(4388)  评论(0编辑  收藏  举报