QR Code Login With Spring Framework, AngularJS And Ionic 4
1.0 (1 rating)
Course Ratings are calculated from individual students’ ratings and a variety of other signals, like age of rating and reliability, to ensure that they reflect course quality fairly and accurately.
12 students enrolled

QR Code Login With Spring Framework, AngularJS And Ionic 4

With Ionic 4 Hybrid Mobile Application and Whatsapp Webapp, Web application. AngularJS, Ionic4, Hibernate, Liquibase
1.0 (1 rating)
Course Ratings are calculated from individual students’ ratings and a variety of other signals, like age of rating and reliability, to ensure that they reflect course quality fairly and accurately.
12 students enrolled
Created by Senol Atac
Last updated 4/2019
English
English, Turkish
Current price: $9.99 Original price: $19.99 Discount: 50% off
3 days left at this price!
30-Day Money-Back Guarantee
This course includes
  • 2 hours on-demand video
  • 3 articles
  • Full lifetime access
  • Access on mobile and TV
  • Certificate of Completion
Training 5 or more people?

Get your team access to Udemy's top 3,000+ courses anytime, anywhere.

Try Udemy for Business
What you'll learn
  • QR Code Login
  • Access Token

  • Ionic 4

  • Mobile Development
  • Spring Messaging
  • QR Code Scanner
  • Java
  • Security
  • Angular 6
  • AngularJS
Course content
Expand all 18 lectures 01:49:06
+ Introduction
3 lectures 12:09

Hi there,


In this lesson, we will start with web application.

And we will prepare our cource materials and we will try to understand general consept of our project.

Let's start.

First of all, we will use Java 1.8 so if you don't have Java 1.8, please download it on your computer.

Secondly, we will go on with Eclipse so if you don't have Eclipse, please download it before cource.

As server application, we will use Tomcat 9, please download it also.

As database tool, we will go on with mysql 5, please download it also.

If Java and Eclipse are downloaded, later we can access to our code template from github.

You can clone with git commands or you can directly download our github project from given link under resources.

Later, If everthing is ok about prerequests, import our project to Eclipse.


Later, to create and update our database, we just need to set database password under resources/application.proporties.

And add your project to Tomcat server.

And change path of project as default under Servers/server.xml.

Now, we can run our project with Tomcat.

If everthing is OK about deployment, you will get a message like Server startup in  ... miliseconds.


OK. Let's look our project folders.

We have config package, this package contains all configurations about project like database configuration and security configuration.

We will go on with Model-Controller-View design pattern, so these three packages will include this design pattern.

The other package is csrf, this is related with cross site security on Spring.

The other one is dao package, this is related with database changes, database access, hibernate queries.

Filter, handler and servlet packages are related with Java http filters, requests and responses.

The last one is utils package, this package is a helper package for others.

In web side, we will go on with angular and this angular things can be found under webcontent.

resources folder conatains libraries about angular and model-view-controller classes.

view folder contains html codes.

Actually, that's all about our code overview.

Thank you and see you.

Preview 07:19
Overview - Application Properties
00:40

Hi there,


In this lesson, we will talk about dependencies and libraries that used on our project.

In our project, we aim to create a system like Whatsapp web application.

So we will need a qr code on web side and we will need a socket listener on browser.

Also, we will need a interactive messaging system for connection between client and server.

So we can listen socket with websocket in server side so spring-websocket will be helpful for it.

Actually, we have already added spring-websocket dependency on our project.

If you have any problem about maven dependencies, please follow these steps.


10 seconds...


On the other hand, we will also need socket in web browser.

To handle it, we will use sockjs. Let's download it.

40 seconds...


To interactive messaging, we will use spring-messaging on server side.

Actually, we have already added spring-messaging dependency on our project.

On client side, we will use stomp.js. Let's download it.

30 seconds.


To qrcode, angular has a lot of libraries so we will use one of them like angular-qrcode.

To download angular libraries, you can use npm command from node.js or you can download code directly from repository.

35 seconds...

But we have already downloaded them to our project so you don't need anything.


That's all for libraries.

Thank you and see you.


In spring web socket can be

npm i angular-qrcode

npm i qrcode-generator

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-websocket</artifactId>

<version>${springframework.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-messaging</artifactId>

<version>${springframework.version}</version>

</dependency>

Dependencies
04:10
+ Web Application
3 lectures 24:26

Hi there,


In this lesson, we will go on with web socket configuration.

We need a web socket broker and hand shake handler.

First of all, we will create a message broker.

Later, we will define broker paths.

Secondly, we will relate stomp and sockjs with handshake.


Let's start.


First of all, we will create a package under config package, name as socket.

Later we will create a new class under socket package, name as WebSocketConfig.


@Configuration

@EnableWebSocketMessageBroker

public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override

    public void configureMessageBroker(MessageBrokerRegistry config) {

        config.enableSimpleBroker("/topic","/queue");

        config.setApplicationDestinationPrefixes("/app");

    }

    @Override

    public void registerStompEndpoints(StompEndpointRegistry registry) {

         registry.addEndpoint("/chat").setHandshakeHandler(new DefaultHandshakeHandler(new TomcatRequestUpgradeStrategy())).withSockJS();

    }

}


That's all about WebSocketConfig.

For last thing, we should add this config class to our main application config class.


AppConfiguration:

@Import({ WebSocketConfig.class })


That's all.

Thank you and see you.


Web Socket Configuration
05:07

Hi there,


In this lesson, we will create interceptor for our message broker.

In previous lesson, we created some brokers.

Web socket will listen these brokers all time like CONNECTING, CONNECTED and DISCONNECTED.

so with interceptors, actually we try to catch this kind of things.


Let's start.


We will create a new class under socket package, name as QRChannelInterceptor.

public class PresenceChannelInterceptor extends ChannelInterceptorAdapter {

    @Override

    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {

        StompHeaderAccessor sha = StompHeaderAccessor.wrap(message);

        if(sha.getCommand() == null) {

            return;

        }

        String sessionId = sha.getSessionId();

        switch(sha.getCommand()) {

            case CONNECT:

//                System.out.println("STOMP Connect [sessionId: " + sessionId + "]");

                break;

            case CONNECTED:

//            System.out.println("STOMP Connected [sessionId: " + sessionId + "]");

                break;

            case DISCONNECT:

//            System.out.println("STOMP Disconnect [sessionId: " + sessionId + "]");

                break;

            default:

                break;

        }

    }

}


Now, we should relate our channel interceptor with web socket.

First of all we create a new bean for ChannelInterceptor.

Later, we will implement to ChannelRegistration.


Please open WebSocketConfig class.


WebSocketConfig:

    @Bean

    public PresenceChannelInterceptor presenceChannelInterceptor() {

        return new PresenceChannelInterceptor();

    }

   

    @Override

    public void configureClientInboundChannel(ChannelRegistration registration) {

        registration.setInterceptors(presenceChannelInterceptor());

    }

   

    @Override

    public void configureClientOutboundChannel(ChannelRegistration registration) {

        registration.taskExecutor().corePoolSize(8);

        registration.setInterceptors(presenceChannelInterceptor());

    }

That's all.

Thank you and see you.

Channel Interceptor
08:23

Hi there,


In this lesson, we will create actions when client is connected and disconnected.

You know that we can catch them with interceptors.


We will create a new token when client is connected.

And we will delete this token when client is disconnected.

You know that using only session id will not be secure so creating token from this session id will save us.


Let's start.

First of all, we will create a new model class, name as MobileToken.

In MobileToken, we will keep session id and access token key.

Later, we will create a new mobile token when client is connected so we should create a database access for Mobile token class.

And last thing, we will delete created token when client is disconnected.


Let's create MobileToken entity under model package.


@Entity

@Table(name="mobile_token")

public class MobileToken implements IModel {

/**

*

*/

private static final long serialVersionUID = -7137200585022971142L;


@Id

@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name="id", columnDefinition="serial")

private Long id;

@Column(name="session_id")

private String sessionId;

@Column(name="access_token")

private String accessToken;

@Temporal(TemporalType.TIMESTAMP)

@Column(name="create_date")

private Date createDate;

@Version

    @Column(name = "version")

    private Long version;

public MobileToken(){

}

public MobileToken(String sessionId, String accessToken, Date createDate) {

super();

this.sessionId = sessionId;

this.accessToken = accessToken;

this.createDate = createDate;

}


public Long getId() {

return id;

}


public void setId(Long id) {

this.id = id;

}


public String getSessionId() {

return sessionId;

}


public void setSessionId(String sessionId) {

this.sessionId = sessionId;

}


public String getAccessToken() {

return accessToken;

}


public void setAccessToken(String accessToken) {

this.accessToken = accessToken;

}


public Date getCreateDate() {

return createDate;

}


public void setCreateDate(Date createDate) {

this.createDate = createDate;

}


public Long getVersion() {

return version;

}


public void setVersion(Long version) {

this.version = version;

}


@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((id == null) ? 0 : id.hashCode());

return result;

}


@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

MobileToken other = (MobileToken) obj;

if (id == null) {

if (other.id != null)

return false;

} else if (!id.equals(other.id))

return false;

return true;

}

}


Later, we will create a database access class for MobileToken.

Let's create a new interface under dao package as IMobileTokenDao.


public interface IMobileTokenDao extends IGenericDao<MobileToken> {

MobileToken findBySessionId(String sessionId);

}


And we will a create MobileTokenDao under dao package.


@Repository

@Transactional

public class MobileTokenDao extends AbstractGenericDao<MobileToken> implements IMobileTokenDao {

@Override

public MobileToken findBySessionId(String sessionId)

{

Query query1 = em.createQuery("Select a from MobileToken a where a.sessionId=:pSessionId");

query1.setParameter("pSessionId", sessionId);

List<MobileToken> user2 = query1.getResultList();

return (MobileToken) DaoUtil.firstOrNull(user2);

}

}


You know we use model view controller pattern so we should call dao object from service side.

Let's open our user service class under services package.


UserService:


@Autowired

    private IMobileTokenDao mobileTokenDao;

    @Override

    public MobileToken createToken(MobileToken token){

    this.mobileTokenDao.save(token);

    return token;

    }

   

    @Override

    public void deleteToken(String sessionId){

    MobileToken daoToken = this.mobileTokenDao.findBySessionId(sessionId);

    if(daoToken!=null){

    this.mobileTokenDao.delete(this.mobileTokenDao.getReference(daoToken.getId()));

    }

    }

IUserService:

MobileToken createToken(MobileToken token);


void deleteToken(String sessionId);


Finally, we will call them from our interceptor class.

QRChannelInterceptor:

        IUserService service = SpringUtils.ctx.getBean(IUserService.class);

        switch(sha.getCommand()) {

            case CONNECT:

            service.createToken(new MobileToken(sessionId, EncriptionUtil.createToken(), new Date()));

//                System.out.println("STOMP Connect [sessionId: " + sessionId + "]");

                break;

            case CONNECTED:

//            System.out.println("STOMP Connected [sessionId: " + sessionId + "]");

                break;

            case DISCONNECT:

            service.deleteToken(sessionId);

//            System.out.println("STOMP Disconnect [sessionId: " + sessionId + "]");

                break;

            default:

                break;

        }

That's all.

Thank you and see you.

Interceptor Actions
10:56
+ Access Token
1 lecture 08:09

Hi there,


In this lesson, we will create user token.

You know in previous lesson, we created mobile token for security of session id but mobile token is not related with user.

So in this lesson, we will create a token for user after creating session token.


Let's begin.

We will create a model class under model package as UserToken.

@Entity

@Table(name="user_token")

public class UserToken implements IModel {

/**

*

*/

private static final long serialVersionUID = 8680170323119326873L;


@Id

@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name="id", columnDefinition="serial")

private Long id;

@Column(name="access_token")

private String accessToken;

@Column(name="session_id")

private String sessionId;

@Column(name="user_id")

private Long userId;

@Temporal(TemporalType.TIMESTAMP)

@Column(name="create_date")

private Date createDate;

@Version

    @Column(name = "version")

    private Long version;

@Transient

private User user;

public UserToken(){

}

public UserToken(String accessToken, Long userId, Date createDate) {

super();

this.accessToken = accessToken;

this.userId = userId;

this.createDate = createDate;

}


public UserToken(String accessToken, String sessionId, Long userId, Date createDate) {

super();

this.accessToken = accessToken;

this.sessionId = sessionId;

this.userId = userId;

this.createDate = createDate;

}


public Long getId() {

return id;

}


public void setId(Long id) {

this.id = id;

}


public String getAccessToken() {

return accessToken;

}


public void setAccessToken(String accessToken) {

this.accessToken = accessToken;

}


public String getSessionId() {

return sessionId;

}


public void setSessionId(String sessionId) {

this.sessionId = sessionId;

}


public Long getUserId() {

return userId;

}


public void setUserId(Long userId) {

this.userId = userId;

}


public Date getCreateDate() {

return createDate;

}


public void setCreateDate(Date createDate) {

this.createDate = createDate;

}


public Long getVersion() {

return version;

}


public void setVersion(Long version) {

this.version = version;

}


public User getUser() {

return user;

}


public void setUser(User user) {

this.user = user;

}


@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((id == null) ? 0 : id.hashCode());

return result;

}


@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

UserToken other = (UserToken) obj;

if (id == null) {

if (other.id != null)

return false;

} else if (!id.equals(other.id))

return false;

return true;

}

}



And we will create dao and service for UserToken.


public interface IUserTokenDao extends IGenericDao<UserToken> {


UserToken findByAccessToken(String token);


}


@Repository

@Transactional

public class UserTokenDao extends AbstractGenericDao<UserToken> implements IUserTokenDao {

@Override

public UserToken findByAccessToken(String token)

{

Query query1 = em.createQuery("Select a from UserToken a where a.accessToken=:pSessionId");

query1.setParameter("pSessionId", token);

List<UserToken> user2 = query1.getResultList();

return (UserToken) DaoUtil.firstOrNull(user2);

}


}


UserService:


@Autowired

    private IUserTokenDao userTokenDao;

@Override

    public UserToken convertUserToken(UserToken token){

    this.deleteToken(token.getSessionId());

    this.userTokenDao.save(token);

    token.setUser(this.userDao.find(token.getUserId()));

    return token;

    }

   

    @Override

    public UserToken findUserToken(String accessToken){

    return this.userTokenDao.findByAccessToken(accessToken);

    }

   

    @Override

    public UserToken createUserToken(UserToken token){

    UserToken daoToken = this.userTokenDao.findByAccessToken(token.getAccessToken());

    if(daoToken==null){

    this.userTokenDao.save(token);

    }else{

    daoToken.setAccessToken(token.getAccessToken());

    daoToken.setUserId(token.getUserId());

    daoToken.setSessionId(token.getSessionId());

    token = this.userTokenDao.update(daoToken);

    }

    return token;

    }

   

    @Override

    public void deleteUserToken(String token){

    UserToken daoToken = this.userTokenDao.findByAccessToken(token);

    if(daoToken!=null){

    this.userTokenDao.delete(this.userTokenDao.getReference(daoToken.getId()));

    }

    }

IUserService:

UserToken findUserToken(String accessToken);


UserToken createUserToken(UserToken token);


void deleteUserToken(String token);


UserToken convertUserToken(UserToken token);

That's all about user token.

We will call these methods later.

Thank you and see you.


User Access Token
08:09
+ Interactive Messaging
3 lectures 31:16

Hi there,


In this lesson, we will implement qr login and qr authentication rest api methods.

First of all, user should read session id with qr scanner and send session id to server side to authentication.

After authentication, user should send session token and user id to login.


Actually, in this lesson we will implement these things.


Let's start.

Pelase open UserRest class under rest package.


@RequestMapping(value = "/qrauth", method = RequestMethod.POST)

public ResponseEntity<MobileToken> qrAuthentication(@RequestBody MobileToken tokenRequest){

MobileToken token = this.userService.findToken(tokenRequest.getSessionId());

if(token==null){

return new ResponseEntity<MobileToken>(HttpStatus.NOT_FOUND);

}

return new ResponseEntity<MobileToken>(token, HttpStatus.OK);

}

tokenRequest will contain just sessionId so we should find mobile token from database by sessionId.

To do it, we should implement findTokenBySessionId in service side.

Let's implement it.

UserService:

    @Override

    public MobileToken findToken(String sessionId){

    return this.mobileTokenDao.findBySessionId(sessionId);

    }

Our other method will be qrLogin after authentication.

This method will convert mobile token to user token.

@RequestMapping(value = "/qrlogin/{token}", method = RequestMethod.POST)

public ResponseEntity<UserToken> qrLogin(@RequestBody UserToken utoken,@PathVariable("token") String token){

try{

    User u = this.userService.findByUniqueId(token);

        if (u == null) {

            return new ResponseEntity<UserToken>(HttpStatus.NOT_FOUND);

        }

MobileToken daoToken = this.userService.findTokenByToken(utoken.getAccessToken());

if(daoToken==null){

return new ResponseEntity<UserToken>(HttpStatus.NOT_FOUND);

}else{

UserToken userToken = this.userService.convertUserToken(new UserToken(EncriptionUtil.createToken(), utoken.getSessionId(), u.getId(), new Date()));

return new ResponseEntity<UserToken>(userToken, HttpStatus.OK);

}

}catch (Exception e) {

e.printStackTrace();

}

return new ResponseEntity<UserToken>(HttpStatus.NOT_FOUND);

}

In that case, we should find mobile token by access token.

So we should implement it also.


MobileTokenDao:

@Override

public MobileToken findByToken(String token)

{

Query query1 = em.createQuery("Select a from MobileToken a where a.accessToken=:pSessionId");

query1.setParameter("pSessionId", token);

List<MobileToken> user2 = query1.getResultList();

return (MobileToken) DaoUtil.firstOrNull(user2);

}


UserService:

    @Override

    public MobileToken findTokenByToken(String token){

    return this.mobileTokenDao.findByToken(token);

    }

That's all.

Thank you and see you.

API Rest Methods
12:33

Hi there,


In this lesson, we will call interactive message after qr login.

You know that after successful qr login, the browser should automatically join the system.

So in this lesson actually we will do this thing.


First of all, to do it we will use a pojo class.

And our class name will be OutputMessage.

Let's create it under model package.


public class OutputMessage {


    private String from;

    private String text;

    private String time;

    private User user;

    private boolean authenticate;

   

    public OutputMessage(){

    }


    public OutputMessage(final String from, final String text, final String time,boolean authenticate) {


        this.from = from;

        this.text = text;

        this.time = time;

        this.authenticate=authenticate;

    }


    public void setFrom(String from) {

this.from = from;

}


public void setText(String text) {

this.text = text;

}


public void setTime(String time) {

this.time = time;

}


public String getText() {

        return text;

    }


    public String getTime() {

        return time;

    }


    public String getFrom() {

        return from;

    }


public boolean isAuthenticate() {

return authenticate;

}


public void setAuthenticate(boolean authenticate) {

this.authenticate = authenticate;

}


public User getUser() {

return user;

}


public void setUser(User user) {

this.user = user;

}

   

}



Now, we will send a message after qr login to client side with Spring MessageSendingOperations.

And this will be asynoric operation so we will use java ExecutorService for it.


Let's do it.


@Autowired

    public SimpMessageSendingOperations messagingTemplate;

ExecutorService executor = Executors.newSingleThreadExecutor();

        final String time = new SimpleDateFormat("HH:mm").format(new Date());

        executor.submit(() -> {

        OutputMessage cht = new OutputMessage();

        cht.setFrom(u.getUniqueId());

        cht.setText("login");

        cht.setTime(time);

        cht.setUser(u);

        cht.setAuthenticate(true);

        jobEnd(utoken.getSessionId(),cht);

           

        });

public void jobEnd(String sessionId, OutputMessage cht){

        messagingTemplate.convertAndSend("/queue/messages-"+sessionId,cht);

    }

That's all.

Tahnk you and see you.

Message Operations
07:17

Hi there,


In this lesson, we will implement WebSocketController.

In WebSocketController, we will catch sending messages in previous lesson with OutputMessage.


Like previous lesson we will use Spring MessageSendingOperations and java executeservice.

We will need a new POJO class in here.

So first of all we will create a new class as ChatMessage.

Later we will implement controller.


Let's start.

We will create ChatMessage under model package.


public class ChatMessage {


private String from;

private String to;

    private String text;

   

public String getTo() {

return to;

}

public void setTo(String to) {

this.to = to;

}

public String getFrom() {

return from;

}

public void setFrom(String from) {

this.from = from;

}

public String getText() {

return text;

}

public void setText(String text) {

this.text = text;

}   

}


Now, we will implement WebSocketController.

We will create a new class under controller package as WebSocketController


@Controller

public class WebSocketController {

@Autowired

    public SimpMessageSendingOperations messagingTemplate;

ExecutorService executor = Executors.newSingleThreadExecutor();

    @MessageMapping("/chat")

    @SendTo("/topic/messages")

    public OutputMessage send(final ChatMessage message, @Header("simpSessionId") String sessionId) throws Exception {

        final String time = new SimpleDateFormat("HH:mm").format(new Date());

        executor.submit(() -> {

            if(message.getTo()!=null && !message.getTo().trim().equals("")){

            jobEnd(message.getTo(),message,time);

            }else{

            jobEnd(sessionId,message,time);

            }

           

        });

        return new OutputMessage(message.getFrom(), message.getText(), time, false);

    }

   

    public void jobEnd(String sessionId, ChatMessage cht, String time){

        messagingTemplate.convertAndSend("/queue/messages-"+sessionId,new OutputMessage(cht.getFrom(), cht.getText(), time, false));

    }


}


That's all about socket controller.

Thank you and see you.

Web Socket Controller
11:26
+ Client Side
2 lectures 15:27

Hi there,


In this lesson, we will create our mobile qr code page.

To do it, first of all we will add previously downloaded stomp.js and sockjs files to our project.

Later we will create a new jsp page.

Finally, we will describe our page from server side.

Let's start.


We will create jms folder under js folder and we will add stomp.js and sockjs files to here.


mobile.jsp:

   

<div class="container qr-container">

<div id="loginbox" style="max-width: 446px;" class="login-custom-box">

<div class="panel" >

   <div style="padding-top:30px" class="panel-body qr-panel-body"  ng-controller="UserController as ctrl">

    <div id="qrfield"><span id="qr-spanner"><i class="fa fa-spinner fa-3x spinning" aria-hidden="true"></i></span> </div>

    </br>

                                <div class="form-group">

                                    <div class="col-md-12 control">

                                        <div style="border-top: 1px solid#888; padding-top:15px; text-align: center;" >

<div>

Scan QR Code with Mobile Application.

</div>

<div><a href="/">Web Login</a></div>

                                        </div>

                                    </div>

                                </div>    

   </div>

</div>

         <footer style="text-align:center;">

               <div class="row">

                   <div class="col-md-12">

                       <div class="center-block" style="margin-top:10px;color: #000;">&copy;All rights are reserved by Senol Atac.</div>

                   </div>

               </div>

       </footer>

</div>

</div>

page.util:

public static final String MOBILE_PAGE = "/mobile";


IndexController: 

@RequestMapping(value="/mobile", method = RequestMethod.GET)

    public String getMobilePage() {

    if(isAuthenticated()){

    return "redirect:/home";

    }

        return "redirect:/#!mobile";

    }


app.js:

    .when("/mobile", {

        templateUrl : "views/public/mobile.jsp",

        publicAccess: true

    })


OK. We just created our mobile page.

That's all.

Thank you and see you.


Mobile Page
06:26

Hi there,


In this lesson, we will learn creating qr code with usign session id.

To do it, we will create a new javascript file and we implement all methods.

Later we call it from our mobile page.

Finally, we will call dependent script from our mobile page and we will complete it.


Let's start.


First of all, we will download jquery.qrcode.min.js and we will add to our project under jms.


mobile_auth.js under jms folder:

var sessionId;

   

   

        var stompClient = null;

$(function(){

$('div[onload]').trigger('onload');

$('qrcode').attr("data",generateUUID());

$('qrcode').attr("href",$('qrcode').attr("data"));

});

    function generateUUID() {

            var d = new Date().getTime();

            if(window.performance && typeof window.performance.now === "function"){

                d += performance.now();; //use high-precision timer if available

            }

            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {

                var r = (d + Math.random()*16)%16 | 0;

                d = Math.floor(d/16);

                return (c=='x' ? r : (r&0x3|0x8)).toString(16);

            });

            return uuid;

        };

       

        function initialize(){

        disconnect();

        setTimeout(function(){ connect(); }, 1000);

        }

       

        function generateQRcode(width, height, text) {

          $('#qrfield').html("");

        $('#qrfield').qrcode({width: width,height: height,text: text});

        }

       

       

        function connect() {

       

            var socket = new SockJS('/chat');

            stompClient = Stomp.over(socket); 

           

            stompClient.connect({}, function(frame) {

            sessionId = /\/([^\/]+)\/websocket/.exec(socket._transport.url)[1];

            generateQRcode(300, 300, sessionId );

                console.log('Connected: ' + sessionId);

                stompClient.subscribe('/queue/messages-'+sessionId, function(messageOutput) {

                    mobileAuthentication(JSON.parse(messageOutput.body));

                    disconnect();

                });

            });

        }

       

        function disconnect() {

       

            if(stompClient != null) {

                stompClient.disconnect();

            }

           

            setConnected(false);

            console.log("Disconnected");

        }

mobile.jsp:

<script src="/resources/js/jms/mobile_auth.js"></script>

<div class="container qr-container" onload="initialize()">

<div><a href="/" onclick="disconnect();">Web Login</a></div>

footer.jsp:

<script src="/resources/bower_components/qrcode-generator/js/qrcode.js"></script>

<script src="/resources/bower_components/qrcode-generator/js/qrcode_UTF8.js"></script>

<script src="/resources/bower_components/angular-qrcode/angular-qrcode.js"></script>

user.controller:

    $window.mobileAuthentication = function(messageOutput){

    if(!messageOutput && !messageOutput.id){

    return;

    }

    self.user=messageOutput.user;

    self.user.ssoId = self.user.uniqueId;

    authorize();

    }

That's all.

Thank you and see you.

QR Generation And Integration
09:01
+ Mobile Application
3 lectures 11:51

Hi there,


In this lesson, we will start to mobile application.

First of all, we will check prerequests about Ionic 4 and our template project.

Then we will check our project structure.

Let's start.


Our first Prerequest is Node.js, if you don't have it, you can download it like that.

Later, you should download android sdk.

Later, you should install ionic cordova with node.js

Later you should install dependencies with npm install command.



We will open our project using with atom.io.

File -> Open folder -> Browse project path


Let's check project structure.

First of all, in ionic all config settings can be done in config.xml

For example, you change name of application or you can change version of application.

Actually, the other important thing folder is src folder.

In src folder, we have app folder.

In app folder, we have pages like home page, login page and app module configuration.

Actually, our mobile diagram is so easy.

When you open application, you will first encounter with login page.

After login, you will encounter a sidemenu.

And sidemenu will contain home page, qr page and result page.

Home page will be welcome page and it has already been ready.

QR page will be QR scanner page and it is also ready.

Our last page is Result page, in this page after scanning qr code from qr page, you will get qr result and you will send it to server side.

Actually, our mission will be this result page task.

That's all.

Thank you and see you.

Overview
05:30

Hi there,


In this lesson we will scan qr code and we will send request to web side from mobile side.

First of all, we will read qr code.

Later, we will send qr code, we will authenticate with qr code and we will get back access Token.

Finally, we will login using with access Token.

Let's start.

To do it we will add some codes to result.page.ts

result.page.ts:


  sessionId: any;

  loader : any;

  mobileToken : any;

  accessToken = "A1B2C3D4E5F6G7";


  ngOnInit() {

  this.sessionId = this.route.snapshot.paramMap.get('id');

this.storage.get('userToken').then((val) => {

  this.accessToken = val;

  this.auth();

});

  }

 

  auth(){

    if(!this.sessionId){

      return;

    }

    this.presentLoading();

      var requestToken = {"sessionId":this.sessionId,"accessToken":this.accessToken};

      this.authService.postData(requestToken,'user/qrauth').then((result) => {

      this.mobileToken = result;

      if(this.mobileToken){

        var userToken = {"sessionId":this.sessionId,"accessToken":this.mobileToken.accessToken};

        this.login(userToken,this.accessToken);

      }

    }, (err) => {

        this.showAlert("Error","Unexpected error occurred.");

        console.log(err.status);

    });

    this.dismissLoading();

  }

 

  login(userToken,val){

    this.authService.postData(userToken,'user/qrlogin/'+val).then((result) => {

  this.dismissLoading();

      this.presentToast("Process is successfully completed.");

    }, (err) => {

        this.showAlert("Error","Unexpected error occurred.");

        console.log(err.status);

    });

  }

That's all.

Thank you and see you.

Scan QR Code and Send It To Server
06:17
Mobile Side - Build And Run
00:04
+ Download Full Code
1 lecture 00:45
Web And Mobile Full Code Links
00:45
Requirements
  • Basic Java Knowledge
  • Basic Spring Knowledge
Description

In this cource, we will learn QR Code Login with mobile + web application.

Mobile application will be constructed with Ionic 4 hybrid (IOS and Android) framework.

Web application will be constructed using with Java, Angular and Spring Framework.

Important Topics:

  • QR Code Login

  • Ionic 4 Mobile Application

  • Angular Web Application

  • Spring Framework Messaging

  • Hibernate

  • Mysql

  • Tomcat

  • Java 1.8

  • Model-view-controller

  • JSP (Java servlet page)

I hope that cource will be so helpful for all developers.

Who this course is for:
  • All developers curious about learning QR Code Login.